Swift Collections: Write and test the code in Swift that meets the following req
ID: 3722068 • Letter: S
Question
Swift Collections: Write and test the code in Swift that meets the following requirements.
States in the USA are abbreviated with two letter codes. For example, Missouri is MO, Pennsylvania is PA, and California is CA.
Declare a variable called states that is declared as a Swift collection type that has elements that have keys which are a state's abbreviation and values that are a state's name. On the declaration line initialize the collection with an empty instance of the collection type.
Add Missouri (MO), Pennsylvania (PA), and California (CA) to the collection.
Using for-in iterate through the key/value pairs of the collection and print them in the format:
<key> is <value>
Obtain an array of all of the state abbreviations in the collection and assign it to a constant called stateCodes.
Iterate through the array of state abbreviations and print each one.
Remove Pennsylvania (PA) from the collection using subscript syntax and assigning a nil.
Remove Missouri (MO) from the collection using the removeValue(forKey:) method on the collection.
Using for-in iterate through the key/value pairs of the collection and print them in the format:
<key> is <value>
The output of your program should look like the following:
PA is Pennsylvania
CA is California
MO is Missouri
PA
CA
MO
CA is California
Explanation / Answer
//most of the coding revolves around declaring and removing a dictionary.Run on swift 4.0
var states=[String:String]()
states["PA"]="Pennsylvania"
states["CA"]="California"
states["MO"]="Missouri"
for (statecode, statename) in states {
print("(statecode) is (statename)")
}
let statecodes = [String](states.keys)
for statecode in statecodes{
print("(statecode)")
}
states.removeValue(forKey: "MO")
states.removeValue(forKey: "PA")
for (statecode, statename) in states {
print("(statecode) is (statename)")
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.