Created
September 26, 2017 00:41
-
-
Save glowcap/d49eaada23dbf0ae157958bcf355f4f5 to your computer and use it in GitHub Desktop.
Handling Optionals in Swift
This file contains hidden or 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
| //: Interview Question - Handling optionals | |
| import UIKit | |
| // There are four common ways to handle optionals | |
| // in Swift | |
| // if let | |
| var myString: String? | |
| myString = "myString" | |
| func printMyString() { | |
| if let myString = myString { | |
| print("myString: \(myString)") | |
| } else { | |
| print("myString is nil") | |
| } | |
| } | |
| printMyString() | |
| // guard | |
| var myInt: Int? | |
| func printMyInt() { | |
| guard let myInt = myInt else { return } | |
| print("myInt: \(myInt)") | |
| } | |
| printMyInt() | |
| // optional chaining | |
| struct User { | |
| let name: String | |
| let password: String | |
| } | |
| var myUser: User? | |
| func printMyUserPassword() { | |
| let password = myUser?.password | |
| print("myUser's password: \(password)") | |
| } | |
| printMyUserPassword() | |
| // force unwrap (handle with care) | |
| var myDouble: Double? | |
| myDouble = 12.14 | |
| func printMyDouble() { | |
| print("myDouble: \(myDouble!)") | |
| } | |
| printMyDouble() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment