-
[Swift] Actor #2 - @MainActor (class 와 같이 사용하기)Swift 2023. 5. 6. 11:57
🎶 인트로
그럼 실제 프로젝트에서는 어떻게 적용하면 좋을까요?
ViewModel 등을 ObservableObject 를 상속해야하기에 class 로 만들어주어야합니다.
이때 등장하는 것이 MainActor 입니다. 코드는 아래와 같습니다.
class 이지만 actor 채택하는 MainActor 를 따르고 있기 때문에 property 값을 참조할때 순서대로 실행이 됩니다.
💻 예시 코드
import Foundation @MainActor class Counter { var count = 0 func increase(times: Int) { for _ in 1...times { Task { count += 1 print(count) } } } } Task { let counter = await Counter() await counter.increase(times: 20) } // 출력 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
📄 설명
아래의 Swift 소스코드를 보면 MainActor -> GlobalActor -> Actor -> AnyActor -> Sendable 를 따르고 있습니다.
그럼 뭔가 Sendable 이란 프로토콜이 가장 중요한 역할을 할것같은 기분이 드는데 다음 글에서 한번 알아보도록 하겠습니다.
📚 참고
MainActor | Apple Developer Documentation
A singleton actor whose executor is equivalent to the main dispatch queue.
developer.apple.com
Nonisolated and isolated keywords: Understanding Actor isolation
The nonisolated and isolated keywords allow you to control Actor isolation and provide access to immutable state within actors.
www.avanderlee.com
'Swift' 카테고리의 다른 글
[Swift] Class Type 검사하기 - isMember(of: ) (0) 2023.05.12 TIL - 비동기에는 비용이 존재한다 (2) 2023.05.06 [Swift] Actor (비동기 환경에서 Data Race 를 피해보자) - #1 (0) 2023.05.06 [Swift] Protocol 을 처음 부터 공부해보자 (0) 2023.05.02 [Swift] 디버그 할때 유용한 기능들 (0) 2023.04.28