我正在尝试Array.reduce()
在自定义类中复制该方法,并意识到它使用Result作为类型。只是不明白是将Result类型创建为Enum还是其他。
import Foundation
public class MyArray {
private var arr: [Int] = []
internal static var instance: MyArray?
private init() {}
public static func getInstance() -> MyArray {
if self.instance == nil {
self.instance = MyArray()
}
return self.instance!
}
public func insert(value val: Int) {
arr.append(val)
}
/*************** Custom reduce like function ***************/
public func perform(_ initialResult: Int, _ nextPartialResult: (Int, Int) -> Int) -> Int {
var result = initialResult
for element in arr {
result = nextPartialResult(result, element) // calling the closure
}
return result
}
}
现在从外部访问MyArray类
var arr1 = MyArray.getInstance()
arr1.insert(value: 1)
arr1.insert(value: 2)
arr1.insert(value: 4)
arr1.insert(value: 3)
arr1.insert(value: 2)
arr1.insert(value: 5)
arr1.insert(value: 2)
arr1.insert(value: 2)
// :Complex calculations left for user to implement
var result = arr1.perform(0) {
return $0 + ( $1 * $1)
}
print("Complex calculation in elements of MEMBER array of arr1: \(result)")
// :Just another way of writing the above closure
result = arr1.perform(0) { (result, num1) -> Int in
return result + ( num1 * num1)
}
print("Complex calculation in elements of MEMBER array of hello arr1: \(result)")
// :Simple calculations
print("Factorial of elements in MEMBER array of arr1: \(arr1.perform(1, *))")
print("Sum of elements in MEMBER array of arr1: \(arr1.perform(0, +))")
问题是我必须一次用一种特定类型(Int或String或Double等)定义我的perform()函数。我正在尝试创建可与任何类型(如reduce()函数)一起使用的函数。
我不明白如何在类中定义Result类型,然后在函数中使用它!
我知道Result类型不是迅速成为标准库的一部分。
标准reduce
函数使用泛型。请参见Swift书中的“泛型”一章。
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
它有两种通用类型:Result
和Element
。Element
来自集合中值的类型,以及Result
来自减少值的结果类型。
因此,第一步是在自己的perform
函数中使用相同的签名。
但是这样做时,您会发现您现在还需要使MyArray
类也基于泛型,而不是硬编码为只能与一起使用Int
。
并且在尝试这样做时,您会发现无法将其定义MyArray
为泛型并不能同时支持单例模式。因此,您需要删除instance
和getIntance()
。
最终结果变为:
public class MyArray<Element> {
private var arr: [Element] = []
public init() {}
public func insert(value val: Element) {
arr.append(val)
}
/*************** Custom reduce like function ***************/
public func perform<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) -> Result) -> Result {
var result = initialResult
for element in arr {
result = nextPartialResult(result, element)
}
return result
}
}
有了这个,您的第一个示例变为:
var arr1 = MyArray<Int>()
arr1.insert(value: 1)
arr1.insert(value: 2)
arr1.insert(value: 4)
arr1.insert(value: 3)
arr1.insert(value: 2)
arr1.insert(value: 5)
arr1.insert(value: 2)
arr1.insert(value: 2)
// :Complex calculations left for user to implement
var result = arr1.perform(0) {
return $0 + ( $1 * $1)
}
print(result)
并输出的所需结果67
。
最后,它是可行的,但是如果您会注意到,那么这MyArray
堂课毫无意义(除了学习练习之外)。只需使用Array
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句