Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
swiftfun
4,039 PointsHow to create function with bools?
How can I create a function to check if a string is either true or false (based on a String:Bool dictionary? Tried using switch and if statements with no luck.
For this example we are controlling the stock of fish.
The function should allow a user to input a fish name (key) and return the value (either true or false) using a print statement ie. print("fishName is not in stock)
The dictionary looks like this:
var fishStock: [String: Bool] = ["Salmon": true, "Tuna": true, "Shrimp" : false]
Can you please suggest
3 Answers
Nathan Tallack
22,164 PointsFirstly, to address your question directly, consider the code below:
var fishStock: [String: Bool] = [
"Salmon" : true,
"Tuna": true,
"Shrimp": false
]
func inStock(fish: String) -> Bool {
// Statically configured to use fishStock dictionary.
// Using if let to verify key exists and return value.
if let result = fishStock[fish] {
return result
} else {
return false
}
}
let haveSalmon = inStock("Salmon") // true
let haveShrimp = inStock("Shrimp") // false
let haveShark = inStock("Shark") // false
You will note that we are taking care to use an if let as the dictionary returns an optional when you are requesting a key with subscript. It returns nil if the key does not exist trigging the else where I return false (as with the haveShark).
See how if a key exists it will return an optional and if it does not it returns a nil. So perhaps your dictionary would be better suited for stock levels rather than bools. You can still return true or false based upon if the key exists, but use the key value to store stock levels instead. Consider the following code.
var fishStock: [String: Int] = [
"Salmon" : 3,
"Tuna": 1,
"Shrimp": 0
]
func inStock(fish: String, stock: [String: Int]) -> Bool {
// Using if let to verify key exists and value > 0 and return true.
if let result = stock[fish] {
if result > 0 {
return true
} else {
return false
}
} else {
return false
}
}
func stockLevel(fish: String, stock: [String: Int]) -> Int {
// Using if let to verify key exists and return value.
if let result = stock[fish] {
return result
} else {
return 0
}
}
let haveSalmon = inStock("Salmon", stock: fishStock) // true
let haveShrimp = inStock("Shrimp", stock: fishStock) // false
let haveShark = inStock("Shark", stock: fishStock) // false
let salmonStock = stockLevel("Salmon", stock: fishStock) // 3
let shrimpStock = stockLevel("Shrimp", stock: fishStock) // 0
let sharkStock = stockLevel("Shark", stock: fishStock) // 0
You will note that we are still taking care to use an if let when accessing the dictionary keys. In the additional function (stockLevel) we are returning the value of the key (the stock level Int in this case) and if the key does not exist we are returning 0 (as with the sharkStock). Additionally you will see we are now passing in the dictionary along with the fish rather than statically coding it to the functions. This is better coding because it means the function is not tied to a single dictionary.
swiftfun
4,039 PointsThank you Nathan for such detailed answer.
The only part I am still trying to make sense of is " if let result = stock[fish]"
It is the first time I see such a use of an IF statement and don't understand what exactly is a constant doing there assigned to "result" and how how does it work.
swiftfun
4,039 PointsOh it seems "if let" is part of Optionals in Swift - And that is a topic I still haven't covered (just finished Functions).
Is there a way to solve my question using a function with a Switch or IF statement, without using Optionals?
Nathan Tallack
22,164 PointsWhen you query a key in a dictionary you will always get an optional back, because if the key does not exist swift will return you the value "nil". This is what makes it an optional.
While it seems quite troublesome to have to deal with it this way, it is a very "safe" thing, and one of the key features of swift. This way you never get caught by surprise expecting a value to be returned and not having one returned, which would cause a crash in other programming languages.
What you could do is build an array of objects by making a class, but that is even more advanced than unwrapping optionals.
Hang in there. Keep working through your courses and it will all make sense. All that I know I learnt from just this few weeks worth of coursework I have done here on treehouse. I promise you, you will get there. And the forum is here for you with any questions you might have. :)