我知道 cos 和 {"cos(\($0))"}
部分会发生什么,但我不明白 nil 中的 {_ 会发生什么
部分。
enum Operation {
case nullaryOperation(() -> Double, () -> String)
}
var operations: Dictionary<String,Operation> = [
"cos" : Operation.unaryOperation(cos, {"cos(\($0))"}, {_ in nil})
]
func performOperation(_ symbol: String) {
if let operation = operations[symbol] {
switch operation {
case .nullaryOperation(let function, let description):
accumulator = (function(), description(), nil)
}
}
}
最佳答案
正如@CodeDifferent 提到的 {_ in nil}
语法意味着:忽略传递给这个闭包的任何内容并始终返回 nil。
考虑这个将闭包作为输入的简单函数。
func myFunc(inputClosure: (arg: Int?) -> Int?){
var num = inputClosure(arg: 2)
print(num)
}
输出等于输入:
myFunc { (arg) -> Int? in
return arg
}
不管输入是什么输出都是1000:
myFunc () { _ -> Int? in
return 1000
}
不管输入是什么,输出都是nil:
// These are the same:
myFunc { (arg) -> Int? in nil
}
myFunc { _ -> Int? in nil
}
关于swift - 有人可以告诉我 { _ in nil } 在这段 Swift 代码中做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44621392/