Printed on: Could 14, 2024
In Swift, we typically wish to assign a property based mostly on whether or not a sure situation is true or false, or possibly based mostly on the worth of an enum. To do that, we are able to both make a variable with a default worth that we modify after checking our situation or we outline a let with no worth so we are able to assign a price based mostly on our circumstances.
Alternatively, you may need used a ternary expression for easy assignments based mostly on a conditional examine.
Right here’s what a ternary seems like:
let displayName = object.isManaged ? object.managedName : object.identify
This code isn’t straightforward to learn.
Right here’s what it seems like if I had written the very same logic utilizing an if assertion as a substitute.
let displayName: String
if object.isManaged {
displayName = object.managedName
} else {
displayName = object.identify
}
This code is far simpler to learn but it surely’s form of bizarre that we’ve got to declare our let
with no worth after which assign our price afterwards.
Enter Swift 5.9’s if and swap expressions
Beginning in Swift 5.9 we’ve got entry to a brand new strategy to writing the code above. We will have swap and if statements in our code that instantly assign to a property. Earlier than we dig deeper into the principles and limitations of this, let’s see how an if expression is used to refactor the code you simply noticed:
let displayName = if object.isManaged {
object.managedName
} else {
object.identify
}
This code combines the perfect of each worlds. We’ve a concise and clear strategy to assigning a price to our object. However we additionally removed a few of the unneeded additional code which implies that that is simpler to learn.
We will additionally use this syntax with swap statements:
let title = swap content material.kind {
case .film: object.movieTitle
case .collection: "S(object.season) E(object.episode)"
}
That is actually highly effective! It does have some limitations although.
Once we’re utilizing an if
expression, we should present an else
too; not doing that leads to a compiler error.
On the time of writing, we are able to solely have a single line of code in our expressions. So we are able to’t have a multi-line if
physique for instance. There’s dialogue about this on the Swift Boards so I’m certain we’ll be capable to have multi-line expressions finally however in the meanwhile we’ll want to ensure our expressions are one liners.