Skip to content

Instantly share code, notes, and snippets.

@hossamghareeb
Created April 2, 2018 15:50
Show Gist options
  • Save hossamghareeb/c123f8cfd96f43be49bd4c47a71528d5 to your computer and use it in GitHub Desktop.
Save hossamghareeb/c123f8cfd96f43be49bd4c47a71528d5 to your computer and use it in GitHub Desktop.
Uncommon ways to handle optionals in Swift
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