Inside the loop, you need to fetch the "favorite drink" entry from the dictionary, and append it to the array:
for character in characters {
if let drink = character["favorite drink"] {
favoriteDrinkArray.append(drink)
}
}
Note, the if let drink =
guards against the possibility there is no such entry in the array – if there isn't, you get a nil
back, and the if
is checking for that, only adding the entry if it's not nil.
You might sometimes see people skip the if let
part and instead just write let drink = character["favorite drink"]!
, with an exclamation mark on the end. Do not do this. This is known as "force unwrapping" an optional, and if there is ever not a valid value returned from the dictionary, your program will crash.
The behavior with the first example is, if there is no drink you don't add it to the array. But this might not be what you want since you may be expecting a 1-to-1 correspondence between entries in the character array and entries in the drinks array.
If that's the case, and you perhaps want an empty string, you could do this instead:
func favoriteDrinksArrayForCharacters(characters: [[String:String]]) -> [String] {
return characters.map { character in
character["favorite drink"] ?? ""
}
}
The .map
means: run through every entry in characters
, and put the result of running this expression in a new array (which you then return).
The ??
means: if you get back a nil
from the left-hand side, replace it with the value on the right-hand side.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…