TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

if for postfix member expressions

Available from Swift 5.5

Paul Hudson      @twostraws

SE-0308 allows Swift to use #if conditions with postfix member expressions. This sounds a bit obscure, but it solves a problem commonly seen with SwiftUI: you can now optionally add modifiers to a view.

For example, this change allows us to create a text view with two different font sizes depending on whether we’re using iOS or another platform:

import SwiftUI

Text("Welcome")
#if os(iOS)
    .font(.largeTitle)
#else
    .font(.headline)
#endif

You can nest these if you want, although it’s a bit hard on your eyes:

Text("Welcome")
#if os(iOS)
    .font(.largeTitle)
    #if DEBUG
        .foregroundColor(.red)
    #endif
#else
    .font(.headline)
#endif

You could use wildly different postfix expressions if you wanted:

let result = [1, 2, 3]
#if os(iOS)
    .count
#else
    .reduce(0, +)
#endif

print(result)

Technically you could make result end up as two completely different types if you wanted, but that seems like a bad idea. What you definitely can’t do is use other kinds of expressions such as using + [4] instead of .count – if it doesn’t start with . then it’s not a postfix member expression.

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.5…

Download all Swift 5.5 changes as a playground Link to Swift 5.5 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.