Skip to content

Instantly share code, notes, and snippets.

@glowcap
Created September 26, 2017 00:41
Show Gist options
  • Select an option

  • Save glowcap/d49eaada23dbf0ae157958bcf355f4f5 to your computer and use it in GitHub Desktop.

Select an option

Save glowcap/d49eaada23dbf0ae157958bcf355f4f5 to your computer and use it in GitHub Desktop.
Handling Optionals in Swift
//: 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