Swift is Apple's new iOS programming language. You can define data structures explicitly. See the generics-style definition in Swift familiar to Java developers.
var favoriteSodas : Dictionary<String, Array<String>>
This can be replaced with the following shorthand
var favoriteSodas : [String: [String]]
"favoriteSodas" is a Dictionary of Arrays. The key is a String.
Defining Data Structures
Swift dispenses with the separate header and implementation files of Objective-C. I initialize my favoriteSodas data structure in an init() method which is like a Java constructor
class FavoriteSodaGenerator {
var favoriteSodas : [String: [String]]
init() {
favoriteSodas = [String: [String]]()
The values of the favoriteSodas Dictionary are Arrays. Here's how I define three Arrays.
class FavoriteSodaGenerator {
var favoriteSodas : [String: [String]]
var carlSodas : [String]
var janeSodas : [String]
var daveSodas : [String]
init() {
favoriteSodas = [String: [String]]()
carlSodas = [String]()
carlSodas.append("coke")
carlSodas.append("7-up")
carlSodas.append("ginger ale")
janeSodas = [String]()
janeSodas.append("diet pepsi")
janeSodas.append("7 up")
janeSodas.append("sprite")
daveSodas = [String]()
daveSodas.append("grape")
daveSodas.append("orange")
daveSodas.append("dr pepper")
I link the Arrays to the dictionary using the following block of code which closes out the init() method.
favoriteSodas["carl"] = carlSodas
favoriteSodas["jane"] = janeSodas
favoriteSodas["dave"] = daveSodas
}
Accessing Arrays
In the challenge, a function is required to return a random item. Based on an input person, this function returns a random item from one of the Arrays in the Dictionary. If not found, and error is returned.
func randomFavoriteSoda(person : String) -> String {
if let sodas_a = favoriteSodas[person] {
let randomIndex = Int(arc4random()) % sodas_s.count
return sodas_a[randomIndex]
} else {
return "Unrecognized person \(person)"
}
}
Testing
Finally, in my AppDelegate, I have the following code that tests the function and data structures.
let favoriteSodaGenerator = FavoriteSodaGenerator()
for index in 0 ..< 2 {
let f = favoriteSodaGenerator.randomFavoriteSoda("carl")
println("Random carl favorite \(index): \(f)")
}
println()
If you've been coding a while, the shorthand syntax won't seem like a big savings. I suspect for beginners or developers coming from a Javascript background, the ability to initialize items with a minimum of syntax will be more appreciated.
No comments:
Post a Comment