Is there a better way to access individual items in each value array and read those into a new array of just the names? How do I get to value [0] in the Chicago Bulls Key more directly? (“Jordan”)
var nbaRoster = ["Chicago Bulls":["Jordan", "Pippen", "Paxon", "Harper",
"Grant"],
"Detroit Pistons":["Thomas","Rodman","Lambeer","Dumars",
"Aguirre"],
"Boston Celtics":["Bird","McHale","Parish","Johnson",
"Ainge"]
]
let nbaPlayers = Array(nbaRoster.values)
var count = 0
var allPlayers: [String] = []
while count < nbaPlayers.count {
allPlayers += nbaPlayers[count]
count += 1
}
print("The NBA has the following players: \(allPlayers)")
// The NBA has the following players: ["Jordan", "Pippen", "Paxon",
"Harper", "Grant", "Bird", "McHale", "Parish", "Johnson", "Ainge",
"Thomas", "Rodman", "Lambeer", "Dumars", "Aguirre"]
This is a safety feature of the language to keep programmers awake at all times
Indexing a dictionary, or indexing any collection for that matter, returns an optional value to make sure that the programmer handles the case of index values that are not valid for the collection.
In the code above, the dictionary ([String:[String]]) is a collection; so are the stored values ([String]).
To go more directly, I nested two FOR loops, the outer looping through each team key, the next looping through each value array. My team names and players were… uninspired.
// Declare the Dictionary
var league = [
"TeamA":
["Player1", "Player2", "Player3", "Player4", "Player5"],
"TeamB":
["Player6", "Player7", "Player8", "Player9", "Player10"],
"TeamC":
["Player11", "Player12", "Player13", "Player14", "Player15"]
]
// Loop through and display only the players!
var returnString = "The league has the following players: "
for team in league.values {
for player in team {
returnString += " \(player)"
}
}
print(returnString)
In general I recommend not being shy about using extra lines and extra variables to make the code more readable. Code is much easier to debug when you can step through it line-by-line to see what changes it’s making. Too many changes to your values on a single line can be difficult to reason with.
This is my solution. Hope that is OK. Sorry for the german expressions.
var buLiTeams = ["Sportfreunde Borken" : ["Willi", "Gerd", "Robbie"],
"TUS Borken" : ["Willy", "Bernd", "Herbert"],
"Viktoria Heiden" : ["Hermann", "Aki", "Andreas"]]
for (key, value) in buLiTeams {
print("\nDer Verein \(key) hat folgende Spieler:\n")
for player in value {
print(player)
}
}
Hello,
Here’s my solution to the challange
let footballTeam = [“Man U” : [“Ik”, “Karl”, “Dozie”, “Kachi”],
“Arsenal” : [“Swarez”, “Neymar”, “Messi”, “Pogba”],
“Man City” : [“Scholes”, “Rooney”, “Rashford”, “Benzema”]
]
var message: [String] =
print("The NWSL has the following players: ", terminator: “”)
for (_, value) in footballTeam {
for v in value {
message.append(v)
}
}
print(message)