관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] @Sendable 개념, 캡쳐하는 변수를 변경하지 못하게 강제화 하는방법 (동시성, 불변성, concurrency, 동시성 프로그래밍) 본문

iOS 응용 (swift)

[iOS - swift] @Sendable 개념, 캡쳐하는 변수를 변경하지 못하게 강제화 하는방법 (동시성, 불변성, concurrency, 동시성 프로그래밍)

jake-kim 2024. 5. 6. 01:13

@Sendable 개념

  • Sendable이라는 의미는 "전달 할 수 있는"이라는 의미이지만, 생략된 의미가 존재
    • @Sendable는 불변성을 보장하는 "전달 할 수 있는"의 의미로 사용
    • 동시성 프로그래밍에서 핵심은 프로퍼티들의 '불변성'을 유지하는 것
    • 프로퍼티들이 '불변성'을 만족한다면, 동시성 프로그래밍에서 쉽게 파라미터, 클로저 등에 넘겨서 처리하는 것에 race condition, dead lock, memory conflict 등의 문제등을 신경쓰지 않고 편하게 프로그래밍이 가능
  • @Sendable의 목적은 값을 변경할 수 없도록 강제화하는것

예제

  • 특정 closure가 있을 때 이 closure에서는 전역변수인 age값 수정이 가능
class ViewController: UIViewController {
    var age = 0
    var closure: ((_ value: Int) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        closure = { [weak self] value in
            self?.age = 1
        }
    }
}
  • 하지만 @Sendable 키워드를 클로저 안에 사용하면 해당 클로저 안에서는 외부의 값을 수정하지 못함
    • 컴파일 에러 발생
class ViewController: UIViewController {
    var age = 0
    var closure: ((_ value: Int) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        closure = { @Sendable [weak self] value in
            self?.age = 1 // compile error: Main actor-isolated property 'age' can not be mutated from a Sendable closure
        }
    }
}

 

* 참고

- https://github.com/apple/swift-evolution/blob/main/proposals/0302-concurrent-value-and-concurrent-closures.md

Comments