swift - Why can I use a constant initialization as if-condition? -


this question has answer here:

while reading official apple guide found this

var optionalname: string? = "john appleseed" var greeting = "hello!" if let name = optionalname {     greeting = "hello \(name)" } 

there constant declaration , assignment i — as beginner — expected expression returning boolean. condition of if statement seems true value, because code inside parentheses being executed.

does initialization of constant return boolean value or if statement can use condition?

this called optional binding. quoting basics -> optionals -> optional binding section of swift language guide.

you use optional binding find out whether optional contains value, , if so, make value available temporary constant or variable. optional binding can used if , while statements check value inside optional, , extract value constant or variable, part of single action.

what if let construct doing checking if someoptional exists. if isn't nil/.none "binds" optional value constant.

if let constantname = someoptional {     ... } 

this can thought of as:

if someoptional != nil {     let constantname = someoptional!     ....  } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -