Swift enumerate functions. How does it work behind?

荒凉一梦 提交于 2019-12-12 09:29:13

问题


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]

That is good. Works.

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

map expects an array as a first parameter, but I put there the tuple as a result of enumerate fnction.

The question is: WHY IT WORKS?


回答1:


It works because in addition to array having a map method, there is a map function that takes any kind of SequenceType:

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

This works not just with arrays, but any kind of sequence – strings, ranges, zipped pairs of sequences, and the result of enumerate, which is also a sequence:

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

EnumerateSequence is a type that holds on to another sequence (in your case, the array [1,2,3]) and then when asked to generate an element, generates the next element from it’s contained sequence along with an incrementing number.




回答2:


You want to look at the following answer: What's the cleanest way of applying map() to a dictionary in Swift?

The map function works on the tuple because it is using the map function from the swift standard library that works on any SequenceType. So it is actually using the index and value of the enumeration, which are the same as the index and element that the map function would use when looking at an array input.



来源:https://stackoverflow.com/questions/28924967/swift-enumerate-functions-how-does-it-work-behind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!