Created
April 2, 2018 15:50
-
-
Save hossamghareeb/c123f8cfd96f43be49bd4c47a71528d5 to your computer and use it in GitHub Desktop.
Uncommon ways to handle optionals in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dic = [String: Int]() | |
dic["hello", default: 0] += 1 | |
dic // ["hello": 1] | |
func parse(_ string: String) -> String { | |
switch Int(string) { | |
case .some(7): return "SEVEN" | |
case 5?: return "FIVE" | |
case let x? where x < 10: return "1-9" | |
default: return "Not valid INT" | |
} | |
} | |
parse("7") // "SEVEN" | |
parse("c") // Not valid | |
parse("5") // "FIVE" | |
parse("8") // "1-9" | |
var arr = [1, 7, 10, nil, 6, nil, 20] | |
for case let x? in arr { // only loop for non nil integers | |
print(x) | |
} | |
// 1, 7, 10, 6, 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment