Directly store value using "if expression" - Swift
Annurdien Rasyid

Annurdien Rasyid @annurdien

About: I'm a regular person who loves to tell computers what to do and make sure they do what I tell them to do.

Location:
Yogyakarta, Indonesia
Joined:
May 28, 2021

Directly store value using "if expression" - Swift

Publish Date: Dec 4 '24
0 0

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

Comments 0 total

    Add comment