swift - 在 swift 中映射高阶函数格式

标签 swift

我想知道为什么 map 格式必须是 {( )} 而不仅仅是 { }

func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {

    // the following is right
    var num1Reduce = nums1.reduce(0){ $0 + $ 1}

    /// the following is wrong ??
    var num2Dict = Dictionary(nums2.map{ $0, 1 }, uniquingKeysWith : +)

    // the following is right
    var num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)

}

我什至看到以下格式({ })。我完全困惑了!

let cars = peopleArray.map({ $0.cars })
print(cars)

最佳答案

您正在使用以下词典initializer :

init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Dictionary<Key, Value>.Value, Dictionary<Key, Value>.Value) throws -> Dictionary<Key, Value>.Value) rethrows where S : Sequence, S.Element == (Key, Value)

请注意,S 是一个序列,其元素是键/值对的元组。

当您将 nums1.map{ ($0, 1) } 传递给第一个参数时,您正在从 nums1 创建一个键/值元组数组。

当您使用 nums2.map{ $0, 1 } 时会失败,因为它缺少元组的括号。

请记住,nums1.map{ ($0, 1) }nums1.map({ ($0, 1) }) 的简写形式。这些都与 trailing closures 有关。这与 { } 中出现的元组的括号无关。

关于swift - 在 swift 中映射高阶函数格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54860147/

相关文章:

ios - 在 AVPlayer 上添加 ActivityIndi​​cator 并删除 addObserver

ios - 如何在swift项目中导入objective c头文件

string - Swift 生成器 : What is the counterpart to next()?

ios - 将 firebase 与 WatchKit 结合使用

swift - 当文本包含回车时滚动到 UITextView 的末尾

swift - 如何在 Swift 中水平居中多个按钮?

swiftui - 如何避免 'Unable to simultaneously satisfy constraints' 错误?

ios - 通过函数 Swift 传递一个类 (UILabel) 及其属性

double 的 Swift 可选和默认值

ios - 如何按总线编号 (buses.number) 对总线对象数组进行排序?