Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does let evaluate a bool value in Swift?

Tags:

swift

I'm reading Swift Programming Language book to get familiar Swift language as many others.

It says that

In an if statement, the conditional must be a Boolean expression—this means that code such as if score { ... } is an error, not an implicit comparison to zero.

What i understand that condition must evaluate a bool value. Even if it's a integer value, it will not work. But what i don't understand is

   if let convertedRank = Rank.fromRaw(3) {
         let threeDescription = convertedRank.simpleDescription() 
}

How does this evaluate a bool value. Normally, we use let to create a constant. As implicit conversion isn't possible in Swift, how does let convertedRank = Rank.fromRaw(3) evaluate a bool value which is a must for condition ?

like image 651
limon Avatar asked Dec 15 '22 22:12

limon


2 Answers

In addition to Bools, if statements can also take optionals, with the condition evaluating to whether or not the optional has a value. This particular construct is called "optional binding".

like image 191
Chuck Avatar answered Jan 08 '23 11:01

Chuck


fromRaw() returns an optional of the type. Because there isn't a Rank for every Int, the function will return either a Rank or nil as a Rank optional. Optionals are the exception to only having Bools in an if condition. If the Optional has a value, it will evaluate as true and if the Optional is nil it will evaluate as false.

like image 30
Connor Avatar answered Jan 08 '23 12:01

Connor