Skip to content

Instantly share code, notes, and snippets.

@polotto
Last active January 29, 2020 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polotto/7e6ec139f9102548754c62537d3f3fb1 to your computer and use it in GitHub Desktop.
Save polotto/7e6ec139f9102548754c62537d3f3fb1 to your computer and use it in GitHub Desktop.

Swift

null check

extension

extension Optional {
    func `let`(do: (Wrapped)->()) {
        guard let v = self else { return }
        `do`(v)
    }
}

var str: String? = "text"
str.let {
    print( $0 ) // prints `text`
}
str = nil

str.let {
    print( $0 ) // not executed if str == nil
}

map

// prints 123
let str1 : String? = "123"
str1.map { print($0) }

// doesn't print anything
let str2 : String? = nil
str2.map { print($0) }

idiomatic

var str: String? = "123"
if let s = str { 
    print(s) 
}

let str2: String? = "123"
guard let strUnwrapped = str2 else { return }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment