Categories
iOS Swift

If-else and switch statements as expressions in Swift

Swift 5.9 arrived with Xcode 15 and one of the new additions to the language is if-else and switch statements as expressions. SE-0380 proposed the new language feature, and we can find in depth information about it there. Let’s go through some of the examples where it comes handy.

Firstly, using if-else or switch for returning values in functions, closures or properties. I write quite a lot of code which just turns an enum value into some other type. Now we can omit the return statement which, in my mind, makes the code much more readable. Here we have an example of returning a different background colour based on the current coffee brewing method.

enum BrewMethod {
case espresso, frenchPress, chemex
}
// Before
func backgroundColor(for method: BrewMethod) -> UIColor {
switch method {
case .espresso: return .systemBrown
case .frenchPress: return .systemCyan
case .chemex: return .systemMint
}
}
// After
func backgroundColor(for method: BrewMethod) -> UIColor {
switch method {
case .espresso: .systemBrown
case .frenchPress: .systemCyan
case .chemex: .systemMint
}
}

Secondly, we can use this new feature for initializing variables with more complex logic without needing to create an immediately executing closure. Personally, I tend to do this quite a lot in my projects. Here is an example of assigning a value to the title variable based on the current brewing method. Note that we can omit return and the closure declaration now.

let method: BrewMethod = .espresso
// Before
let title: String = {
switch method {
case .espresso: return "Espresso"
case .frenchPress: return "French Press"
case .chemex: return "Chemex"
}
}()
// After
let title2: String =
switch method {
case .espresso: "Espresso"
case .frenchPress: "French Press"
case .chemex: "Chemex"
}

Here is another example where we use if-else statement for the same purpose. Especially handy to contain some more complex logic.

let method: BrewMethod = …
let hasSelection = …
let bannerText =
if !hasSelection {
"Please select a brewing method"
}
else if method == .chemex {
"Yada yada"
}
else {
"Other yada yada"
}

If this was helpful, please let me know on Mastodon@toomasvahter or Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.