Skip to content

Instantly share code, notes, and snippets.

@zionsg
Last active February 23, 2023 05:08
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 zionsg/2514d6f4c28362822eab32597b5d9aaa to your computer and use it in GitHub Desktop.
Save zionsg/2514d6f4c28362822eab32597b5d9aaa to your computer and use it in GitHub Desktop.

TIL in Swift, s in let s = optionalString will be unwrapped when used with if and guard.

var possibleString: String?
possibleString = "Hello"

/* if without unwrap */
let s = possibleString
if (s != nil) {
    print(s) // Optional("Hello")
}

/* if with unwrap */
if let s = possibleString {
    print(s) // "Hello"
}

/* guard without unwrap */
func check(optionalString: String?) {
    let s = optionalString
    guard (s != nil) else {
        print("nil value")
        return
    }

    // Warning: Expression implicitly coerced from 'String?' to Any
    print(s) // Optional("Hello")
}

/* guard with unwrap */
func checkAndUnwrapped(optionalString: String?) { 
    guard let s = optionalString else {
        print("nil value")
        return
    }

    print(s) // "Hello"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment