Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of array returned by map

Tags:

swift

swift2

This just popped in my head as one of though "I know how it works but don't know what it's supposed to be moment". Let's say I have an array:

struct Person {
    var name : String
    var age : Int
}

var people = [Person]()
people.append(Person(name: "John", age: 24))
people.append(Person(name: "Mike", age: 21))
people.append(Person(name: "Emma", age: 23))

And I want to map people to two different arrays with names and ages:

let names = people.map { $0.name }
let ages  = people.map { $0.age }

Questions:

  1. Is there a guarantee that the result will be in the order of the original array, i.e. names = ["John", "Mike", "Emma"] and ages = [24, 21, 23]?

  2. If the answer to the first question is no, is there a guarantee that names and ages are in sync?

like image 920
Code Different Avatar asked Jul 11 '15 15:07

Code Different


1 Answers

Yes, and here's your source.

"After applying the provided closure to each array element, the map(_:) method returns a new array containing all of the new mapped values, in the same order as their corresponding values in the original array."

like image 68
36 By Design Avatar answered Sep 30 '22 15:09

36 By Design