在swift中映射高阶函数格式

问题描述 投票:2回答:2

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

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)
swift
2个回答
1
投票

您正在使用以下Dictionary 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有关,这与{ }中出现的元组的括号无关。


1
投票

map是一个以闭包为参数的函数。我们可以调用map并传递参数,就像我们对任何其他普通函数调用一样,而不删除括号()e.g

(0...100).map ({ _ in print("yeti")})

但是swift允许我们删除括号作为一种短暂的方式,我们可以写它,因此消除了()

(0...100).map { _ in print("yeti")}

但是如果你想访问数组元素的各个值,你可以用两种方式来实现,

  1. 给定一个数组,你可以使用$ 0访问它的单个元素,基本上就是Hey map, give me the first element at this current index
(0...100).map {$0}
  1. 您可以通过为其提供可读的变量名来决定定义要访问的值,而不是使用默认的swift索引
(0...100).map {element in}

这得到$0并将其分配给elementin关键字基本上告诉编译器嘿,$0现在是element,我们将在in之后使用它。否则,如果删除in关键字,编译器会说它不知道任何名为element的变量。

对于像字典这样的特殊集合,它们每个索引有两个值,即keyvalue,因此如果你想在映射期间访问字典的内容,你可以用上面两种方式来做,a)。使用默认的swift索引,或者给出每个索引的值,可读的变量名。例如

let dictionary = ["a": 3, "b": 4, "c": 5]
dictionary.map{($0, $1)}

我们使用内部括号()让编译器知道我们映射的集合每个索引有两个值。请注意,内括号正在创建一个元组

dictionary.map {(key, value) in }
© www.soinside.com 2019 - 2024. All rights reserved.