gpt4 book ai didi

swift - 快速映射高阶函数格式

转载 作者:可可西里 更新时间:2023-11-01 01:07:30 27 4
gpt4 key购买 nike

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

最佳答案

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com