fupio

Fupio çevrimiçi paylaşmanın en kolay yolu Daha fazla bilgi »

Fupio'ya katıl
Hacking with Swift

Hacking with Swift

This is another good year for SwiftUI, with another batch of scrollview improvements, some welcome macOS features, remarkable control over text rendering, and more – the team at Apple have a lot to be proud of, and many developers will breathe a sigh of relief as API such as fine-grained subview control is now public for all of us to use.
But there's also one major architectural change you need to be aware of, so let's start with that…

View is now on the main actor

For a long time, the View protocol looked a bit like this:
protocol View {
    @MainActor var body: some View
}
That meant code in your view's body ran on the main actor, but code elsewhere in your view did not.
This allowed our views to do work across tasks naturally, but caused problems when using @Observable classes that ran on the main actor. For example, code like this simply wouldn't compile:
@Observable @MainActor
class ViewModel {
    var name = "Anonymous"
}

struct ContentView: View {
    @State private var viewModel = ViewModel()

    var body: some View {
        Text("Hello, \(viewModel.name)!")
    }
}
That would throw up "Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context", which is a rather complex way of saying "your class says it must be on the main actor, but you're creating it away from the main actor."
When you rebuild your code with Xcode 16 that error goes away completely, and with no work from us – it's just gone. However, it's important to know why. You see, the View protocol now looks more like this:
@MainActor protocol View {
    var body: some View
}
The difference is small, but makes a huge difference: the @MainActor attribute moved from body up to the protocol itself, which means the body property along with all other properties and methods we make are run on the main actor.
You can see the impact with this sample code:
struct Co...
https://www.hackingwithswift.com/articles/270/whats-new-in-swiftui-for-ios-18

Comments