Save 37% off PRO during our Black Friday Sale! »

Property Wrappers

9f33218af7ae5c04e102fcc3076f2f5c?s=47 yhkaplan
January 21, 2020

Property Wrappers

9f33218af7ae5c04e102fcc3076f2f5c?s=128

yhkaplan

January 21, 2020
Tweet

Transcript

  1. Property Wrappers 1

  2. What are they? 2

  3. → New in 5.1 → Java-like annotations → Can accept

    (generic) parameters → Used in SwiftUI 3
  4. Purpose 4

  5. Examples 5

  6. SwiftUI 6

  7. struct ContentView: View { @State private var value = 0.0

    var body: some View { VStack { Text("Value is \(value)") Slider(value: $value) } } } 7
  8. UIKit/ Foundation 8

  9. class ViewController: UIViewController { @Keychain(key: "secret_info") var secretInfo = ""

    } 9
  10. Let's make one! 10

  11. @propertyWrapper struct TwelveOrLess { private var number = 0 var

    wrappedValue: Int { get { return number } set { number = min(newValue, 12) } } } // Use struct S { @TwelveOrLess var num = 13 // 12 } 11
  12. @propertyWrapper struct Clamped { private var number = 0 private

    let maxNum: Int private let minNum: Int var wrappedValue: Int { get { return number } set { number = max(min(newValue, maxNum), minNum) } } } // Use struct S { @Clamped(maxNum: 10, minNum: 0) var num = 13 // 10 } 12
  13. Projected values 13

  14. @propertyWrapper struct State<T> { //... var projectedValue: Binding<T> } 14

  15. struct ContentView: View { @State private var isDisabled = false

    var body: some View { OtherView($isDisabled) // Binding<Bool> } } 15
  16. Conclusion 16

  17. More info 17

  18. → The Swift Programming Language → Burritos 18