【发布时间】:2018-07-05 13:13:47
【问题描述】:
我试图在我的自定义类中复制 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 类型不是 swift 标准库的一部分。
【问题讨论】:
-
不相关,但
getInstance()方法是 objective-c-ish 且毫无意义。只需写static let instance = MyArray()(称为MyArray.instance)并删除整个getInstance()方法。static变量在 Swift 中默认是惰性创建的。
标签: swift closures higher-order-functions