I'm new to Swift and is learning the concept of Array. I saw the code below from "swift programming language 2.1".
var array = [1,2,3,4,5]
for (index, value) in array.enumerate() {
print("\(value) at index \(index)")
}
I want to read a bit more about the enumerate()
func so I looked up the Apple developer's page on Array, however, I could not find a func named enumerate()
on this page. Am I looking at the wrong place or is there something I am missing? Coudl someone please give me a hand? Thanks in advance for any help!
When you encounter a Swift standard library function or method that you can't find documentation on, command-click on it in Xcode. That will take you to its definition, which in this case is
extension SequenceType {
/// Return a lazy `SequenceType` containing pairs (*n*, *x*), where
/// *n*s are consecutive `Int`s starting at zero, and *x*s are
/// the elements of `base`:
///
/// > for (n, c) in "Swift".characters.enumerate() {
/// print("\(n): '\(c)'")
/// }
/// 0: 'S'
/// 1: 'w'
/// 2: 'i'
/// 3: 'f'
/// 4: 't'
@warn_unused_result
public func enumerate() -> EnumerateSequence<Self>
}
What the above states is that enumerate()
gives you back a tuple for each value in your collection, with the first element in the tuple being the index of the current item and the second being the value of that item.