http://stackoverflow.com/questions/29322977/whats-the-difference-between-if-nil-optional-and-if-let-optional
if let optional binding
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var haha : String? = nil if let temp = haha { // takes optional 'haha' as input //gives you back required constant 'temp' if optional 'haha' is not nil print("valid, result is: \(temp)"); //This is intended for the common code pattern where you first check to see if a value is nil, //and if it's not, you do something with it. } else { // If the optional is nil, processing stops and the code inside the braces is skipped. print("invalid"); } |
The if let syntax is called optional binding. It takes an optional as input and gives you back a required constant if the optional is not nil. This is intended for the common code pattern where you first check to see if a value is nil, and if it’s not, you do something with it.
If the optional is nil, processing stops and the code inside the braces is skipped.
optional !=nil
1 2 3 4 5 6 |
if haha != nil { // haha is an optional print("\(haha!), is valid"); } else { print("its nil!") } |
The if optional != nil syntax is simpler. It simply checks to see if the optional is nil. It skips creating a required constant for you.
The optional binding syntax is wasteful and confusing if you’re not going to use the resulting value.
Use the simpler if optional != nil version in that case. It generates less code, plus your intentions are much clearer. The main difference is in readability. Using optional binding creates the expectation that you are going to use the optional that you bind.