5 hours ago · 5 min read1066 words · Tech · hide · 0 comments

In Swift, the @MainActor attribute can be used to associate a given type, function, or value with the global main actor, which essentially makes any such code operate on the enclosing app’s main thread. That’s incredibly useful for things like UI-related code, since UI updates (whether done using UIKit, SwiftUI, or another framework) most often need to be performed on the main thread. But how does all of this work when it comes to declaring and adopting protocols?The main actor as a requirementJust like concrete types, a Swift protocol can be fully isolated to the main actor, which means that all of its members (which in the case of a protocol are its list of requirements, and any extensions we’ve added) in turn also become main actor isolated. For example, here we’ve declared an ErrorPresenter protocol, which is annotated with the @MainActor attribute:@MainActor protocol ErrorPresenter { func presentError(_ error: Error, fromView view: UIView) func presentRecoverableError( _ error:…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.