On which thread is the init method executed?
sobes.tech AI
Answer from AI
Primarily, on the thread from which the instance was created. There is no explicit restriction on executing init methods on a specific thread.
However, consider the following features:
-
Main Actor: If a class or struct is marked as
@MainActor, their initialization by default will be performed on the main thread, even if the instance creation call was made from another thread. This is related to Actor Isolation.@MainActor class MyClass { init() { // This code runs on the main thread, even if called from a background thread. } } -
Using asynchronous primitives: Async/await and other tools can influence the execution context, but the
initmethod itself remains synchronous. If an asynchronous function is called insideinit, the asynchronous part will execute in the appropriate context (for example, on the default thread pool forawait), but the code before and afterawaitininitwill run on the thread whereinitstarted. -
UIKit/AppKit: Some UI components should only be used on the main thread. Initialization of such components (e.g.,
UIView) should occur on the main thread, otherwise errors or incorrect behavior may arise.
In most cases, if there are no explicit restrictions (like @MainActor) or interactions with UI, init simply executes on the calling thread. If you need to perform asynchronous work or heavy computations during initialization, it is better to move this logic outside init and perform it asynchronously after creating the object.