-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathoptionals.swift
More file actions
33 lines (24 loc) · 904 Bytes
/
optionals.swift
File metadata and controls
33 lines (24 loc) · 904 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Foundation
// As an alternative to multiple return values (Go)
// Or Exceptions (every other language)
// Optionals are used to handle failure cases when
// you're good and ready. Sorta like a lightweight
// Maybe monad, without the FP hoity-toity.
var one = "1"
var intVal = Int(one)
// Use a if-check to determine if there's an underlying value.
if let intVal = Int(one) {
// And then access the underlying value with !
print(intVal) // 1
}
var nope = "please"
var nopeIntVal = Int(nope)
if nopeIntVal == nil {
print("Couldn't convert the string to an int")
}
// Creating optionals.
var maybe:String? = nil
print(maybe) // nil
print(maybe == nil) // true
maybe = "yep"
print(maybe) // yep