WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

self is no longer required in many places

Available from Swift 5.3

Paul Hudson      @twostraws

SE-0269 allows us to stop using self in many places where it isn’t necessary. Prior to this change, we’d need to write self. in any closure that referenced self so we were making our capture semantics explicit, however often it was the case that our closure could not result in a reference cycle, meaning that the self was just clutter.

For example, before this change we would write code like this:

struct OldContentView: View {
    var body: some View {
        List(1..<5) { number in
            self.cell(for: number)
        }
    }

    func cell(for number: Int) -> some View {
        Text("Cell \(number)")
    }
}

That call to self.cell(for:) cannot cause a reference cycle, because it’s being used inside a struct. Thanks to SE-0269, we can now write the same code like this:

struct NewContentView: View {
    var body: some View {
        List(1..<5) { number in
            cell(for: number)
        }
    }

    func cell(for number: Int) -> some View {
        Text("Cell \(number)")
    }
}

This is likely to be extremely popular in any framework that makes heavy use of closures, including SwiftUI and Combine.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 5.3…

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

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.