John John - 5 days ago 5
Swift Question

" if let " must be used only for optional ? (Swift)

Question 1: if let must be used only for optional

Question 2: If yes for question 1 , Does "if let " evaluate true or false or something ? Because we use this in a " if condition " and only way " if condition " works is to evaluate true or false. Here example :

var something:String? = " Hello "

if let makeSomethingNew = something {
let final = makeSomethingNew + something
}


let makeSomethingNew = something evaluates true here ?

Answer

Question 1

if let is knowns as optional binding.

It only works on Optionals. The following code would generate an error:

var str = "Hello, playground"

if let x = str {
    print("success") // error: initializer for conditional binding must have Optional type, not 'String'
}

Why? Because if let is only used for optionals, String is not an optional.

Question2

And yes it evaluates if the optional has been set ie has a value.

For more info see this answer

Additional question I am adding: Why are we doing such?

Because optionals are either set or not ( have a value or not). We want to only do something if they have a value. If they don't have a value, we don't want to do anything (we don't want to crash either).

You also use it to unwrap the optional.

var optionalString : String? = "hi"

if let unwraped = optionalString {
    print (unwraped) // hi | easier to work with
    print(optionalString) // Optional("hi") | not so easy to work with
}
Comments