map
is a transform function. It takes a sequence of one type of thing and returns a sequence of another type of thing. The type of thing it takes depends on what map
is being called on.
Here is the signature for map
from the Swift Standard Library's Array
:
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
Ignoring the throws
and rethrows
, which just indicates how the function can handle errors, we see that map
takes an Element
(i.e., one item of whatever sequence it's being called on) and returns some type T
.
In this case, it is being called on mission.crew
, which is an array of CrewRole
. So what is being passed into map
is a single CrewRole
item.
And what is being returned from map
? Well, we are assigning the result to self.crew
, which has been declared as [CrewMember]
, or an array of CrewMember
items.
(We will ignore the fatalError
since that just causes your app to crash instantly and so it has no return type.)
member
here is simply the CrewRole
item that is being passed in to map
using trailing closure syntax.
The signature for this closure would therefore be:
map(_ transform: (CrewRole) -> CrewMember) -> [CrewMember] //again, ignoring throws and rethrows
So, to sum up: mission.crew.map
:
-
feeds each item in an array of CrewRole
items into a closure
-
the closure transforms a CrewRole
into a CrewMember
(how? see below)
-
map
returns an array of CrewMember
items
Make sense?
As for astronauts: [String: Astronaut]
...
[String: Astronaut]
indicates that astronauts
is a Dictionary
. Dictionaries are collections that store values by a key. Just like a real-world dictionary allows you to look up definitions by a keyword, a programming Dictionary
allows you to look up values by a key.
A Dictionary
type is indicated as such: [Key: Value]
. So the astronauts
declaration is telling us that it is a dictionary with a key of String
and a value of Astronaut
. In other words, you can find an Astronaut
by querying the astronauts
dictionary with a String
key. IIRC, that String
key is each astronaut's name, but it's been a while since I looked at the Moonshot code.
So here in this init
function, the closure given to the map
function:
-
takes the CrewRole
item passed in as member
-
uses its name
property as a key to look up a corresponding Astronaut
in the astronauts
dictionary
-
builds a CrewMember
struct using the member
's role
property and the Astronaut
item retrieved from the Dictionary
-
returns this new CrewMember
item so that map
can stitch all of them together into an array