Skip to content

Commit db15991

Browse files
committed
Update README.md
1 parent cdc3cc1 commit db15991

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

README.md

+43
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,49 @@ class ViewController: UIViewController {
3434

3535
}
3636
```
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+
```
3780

3881
## License
3982
AssociatedObject is released under the MIT License. See [LICENSE](./LICENSE)

0 commit comments

Comments
 (0)