// // main.swift // PropertyWrapper // // Created by Guy Lapalme on 2023-07-21. // import Foundation @propertyWrapper struct Die { private var number:Int! // implicitly unwrapped optional to allow "limit" call in init() init(wrappedValue:Int){ number = limit(wrappedValue) } var wrappedValue: Int { get { number+1 } set { number = limit(newValue) } } var projectedValue:String { get {["one","two","three","four","five","six"][number]} } private func limit(_ val:Int) -> Int { return max(0,(val-1)%6) } } func TestWithoutPW() { print("start : TestWithoutPW") var d = Die(wrappedValue: 10) print("after init",d.wrappedValue,d.projectedValue) d.wrappedValue = 1 print("after assigning 1",d.wrappedValue,d.projectedValue) d.wrappedValue = 2*d.wrappedValue + d.wrappedValue print("after 2*d+d",d.wrappedValue,d.projectedValue) d.wrappedValue = 100 print("after assigning 100",d.wrappedValue,d.projectedValue) print("========") } func testWithPW(){ print("start : TestWithPW") @Die var d = 10 print("after init",d,$d) d = 1 print("after assigning 1",d,$d) d = 2*d + d print("after 2*d+d",d,$d) d = 100 print("after assigning 100",d,$d) print("PW",_d,_d.projectedValue,_d.wrappedValue) for i in 1...10 { d=i print(i,d) } print("----------") } TestWithoutPW() testWithPW()