Language/Swift

[SwiftUI] WWDC23 Discover Observation in SwiftUI

jaewpark 2023. 9. 17. 00:08

Observation

  • define model
  • UI respond to changes to that model
  • developing with SwiftUI seamless and intuitive(원활하고 직관적)

What is Observation?

Observation

  • new Swift feature
  • tracking changes to properties
  • New in Swift 5.9
  • new macro system
@Observable class FoodTruckModel {
    var orders: [Order] = []
    var donuts = Donut.all
}

@Observable

  • Macro
    관찰할 수 있는 형식으로 확장
    컴파일러에게 변환하도록 지시
  • Tracks access
    해당 속성에 대한 액세스를 추적
    다음 속성이 해당 관찰에서 변경되는 시기를 관찰
  • Property changes cause UI updates
    변경될 때만 body of views를 다시 계산
    환상적인 성능 향상

SwiftUI property wrappers

primary property wrappers

State

  • 뷰가 모델에 own state를 저장해야 하는 경우에 사용
  • 편집 가능한 필드에 값을 바인딩
  • 해당 propertyproperty가 포함된 뷰의 수명에 따라 관리

Environment

  • 전역적으로 액세스 가능한 값으로 전파
  • Observable 은 생성된 업데이트가 액세스를 기반으로 하기 때문에 환상적으로 작동
  • Observable property가 변경되면 view가 업데이트

 

Bindable

  • Lightweight
  • Connect reference to UI
  • Uses $ syntax to create bindings

Advanced uses

SwiftUI

  • 인스턴스당 필드에 대한 액세스를 추적
  • arrays, optionals, any type that contains observable models를 사용할 수 있음을 의미

array of observable models 혹은 model types that contain other observable model types을 가질 수도 있습니다. 사용되는 property가 변경되면 view는 업데이트됩니다.

Computed properties

  • SwiftUI tracks access
  • Other Observation properties으로 구성되어도 작동
  • Manual control when needed

ObservableObject

Observable macro

  • simplify code
  • decent performance boost

remove ObservableObject, @Published

@ObservedObject@Environment로 변환
바인딩은 새로운 @Bindable로 변경


 

 

Discover Observation in SwiftUI - WWDC23 - Videos - Apple Developer

Simplify your SwiftUI data models with Observation. We'll share how the Observable macro can help you simplify models and improve your...

developer.apple.com