gpt4 book ai didi

Swift 枚举函数。背后是如何运作的?

转载 作者:行者123 更新时间:2023-11-28 13:16:12 25 4
gpt4 key购买 nike

The enumerate function returns a tuple for each item in the array composed of the index and the value for that item.

The map function returns an array of elements built from the results of applying a provided transforming closure for each element in the array.

Declaration:

func map<U>(transform: (T) -> U) -> [U]
var numbers = [1, 2, 3]
numbers = map(numbers) { (index, element) in
index + element
} //[1, 3, 5]

这很好。作品。

var numbers = [1, 2, 3]
var result = map(enumerate(numbers)) { (index, element) in
index + element
} //[1, 3, 5]

map 需要一个数组作为第一个参数,但我将元组放在那里 作为枚举函数的结果

问题是:为什么有效?

最佳答案

之所以有效,是因为除了具有 map 方法的数组外,还有一个 map 函数可以接受任何类型的 SequenceType:

func map<S : SequenceType, T>(source: S, transform: (S.Generator.Element) -> T) -> [T]

这不仅适用于数组,还适用于任何类型的序列——字符串、范围、压缩序列对以及 enumerate 的结果,它也是一个序列:

// enumerate is a function that takes any kind of sequence, and returns 
// an EnumerateSequence object
func enumerate<Seq : SequenceType>(base: Seq) -> EnumerateSequence<Seq>

EnumerateSequence 是一种类型,它保留另一个序列(在您的例子中,数组 [1,2,3]),然后在被要求生成一个元素时, 从它包含的序列中生成下一个元素以及一个递增的数字。

关于Swift 枚举函数。背后是如何运作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28924967/

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