File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -34,6 +34,49 @@ class ViewController: UIViewController {
34
34
35
35
}
36
36
```
37
+ ### willSet/didSet
38
+ Properties defined using ` @AssociatedObject ` can implement willSet and didSet.
39
+ In swift, it is not possible to implement ` willSet ` and ` didSet ` at the same time as setter, so they are expanded as follows.
40
+
41
+ ``` swift
42
+ @AssociatedObject (.OBJC_ASSOCIATION_COPY_NONATOMIC )
43
+ public var hello: String = " こんにちは" {
44
+ didSet {
45
+ print (" didSet" )
46
+ }
47
+ willSet {
48
+ print (" willSet: \( newValue ) " )
49
+ }
50
+ }
51
+
52
+ // ↓↓↓ expand to ... ↓↓↓
53
+ public var hello: String = " こんにちは" {
54
+ get {
55
+ objc_getAssociatedObject (
56
+ self ,
57
+ & Self .__associated_helloKey
58
+ ) as? String
59
+ ?? " こんにちは"
60
+ }
61
+
62
+ set {
63
+ let willSet: (String ) -> Void = { newValue in
64
+ print (" willSet: \( newValue ) " )
65
+ }
66
+ willSet (newValue)
67
+ objc_setAssociatedObject (
68
+ self ,
69
+ & Self .__associated_helloKey ,
70
+ newValue,
71
+ .OBJC_ASSOCIATION_COPY_NONATOMIC
72
+ )
73
+ let didSet = {
74
+ print (" didSet" )
75
+ }
76
+ didSet ()
77
+ }
78
+ }
79
+ ```
37
80
38
81
## License
39
82
AssociatedObject is released under the MIT License. See [ LICENSE] ( ./LICENSE )
You can’t perform that action at this time.
0 commit comments