DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on

Day 12 of 100 days of SwiftUi

I just completed day 12 of 100 days of SwiftUi. Today, I learnt about the optional type in Swift.

The optional type is a Swift feature that is used to signify a type that may not have no value at all. Optional types in Swift are represented with a ?. For example

var gender? = nil
Enter fullscreen mode Exit fullscreen mode

The code above is an optional type that stores the gender of a user. Some users may not input their gender so we need to use an optional here to signify this value gender may not have a value.

Getting a value from an Optional is rather simple using the if-let or the gaurd-let.

The if-let is a conditional statement that is used to get the value from an optional.
For example, you can get the value from gender? like this

if let selectedGender = gender{
  print ("\(selectedGender)")
} else {
  print (" No gender selected")
}
Enter fullscreen mode Exit fullscreen mode

The if-let runs the code in the else block if the optional has no value.

The gaurd-let is very similar to the if-let. The only difference is there is no else block. The guard let returns from the function if the optional has no value.

Top comments (0)