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

标签 swift enumerate

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/

相关文章:

swift - 简单 swift 脚本的段错误

iOS 电话号码幻灯片菜单

swift - Gigya 在 Swift 项目初始化期间崩溃

swift - swift 范围内的 "intervals"是什么?

swift - 在 UICollectionView 中选择单个 UILabel

python - 在 CSV python 中添加列并枚举它

windows - 为 OpenGL 渲染枚举设备和显示模式

python - For循环枚举。 Python

windows - Windows是否保留了A和B驱动器?

python - 理解Python的枚举