我想知道为什么 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/