DEV Community

Annurdien Rasyid
Annurdien Rasyid

Posted on

Directly store value using "if expression" - Swift

When we want to set a variable for a specific condition, this what we normally do:

let temperatureInCelsius = 25 let weatherAdvice: String if temperatureInCelsius <= 0 { weatherAdvice = "It's very cold. Consider wearing a scarf." } else if temperatureInCelsius >= 30 { weatherAdvice = "It's really warm. Don't forget to wear sunscreen." } else { weatherAdvice = "It's not that cold. Wear a T-shirt." } print(weatherAdvice) // Prints "It's not that cold. Wear a T-shirt." 
Enter fullscreen mode Exit fullscreen mode

We can make it more cleaner using if expression:

let temperatureInCelsius = 25 let weatherAdvice = if temperatureInCelsius <= 0 { "It's very cold. Consider wearing a scarf." } else if temperatureInCelsius >= 30 { "It's really warm. Don't forget to wear sunscreen." } else { "It's not that cold. Wear a T-shirt." } print(weatherAdvice) // Prints "It's not that cold. Wear a T-shirt." 
Enter fullscreen mode Exit fullscreen mode

Learn more:

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow#Conditional-Statements

Top comments (0)