swift - 有人可以告诉我 { _ in nil } 在这段 Swift 代码中做了什么

标签 swift dictionary

我知道 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/

相关文章:

ios - 应用程序运行时 swift sourceApplication 不工作

swift - performBackgroundTask() 中的 perform() 和 performAndWait() 是否需要,可以使用吗?

javascript - 如何根据字典中的不同值返回键的值

python - 我有一个列表,其中每个元素都是列表中的单个数字。如何提取数字?

python - python语法中的namedtuple与内置类型和orderedDict相比很奇怪

python - 如何从字典中提取值并从中创建列表

swift - 将 self 转换为 UnsafeMutablePointer<Void> 导致 EXC_BAD_INSTRUCTION

带有范围按钮的导航栏中的 iOS 11 搜索 Controller

swift - 字符串替换发生为\character 生成错误

python - Pandas :根据字典更改数据框值并删除不匹配的行