Skip to content

Commit 8ae1150

Browse files
committed
playing with key paths some more
1 parent 54e373e commit 8ae1150

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

bk1ch10p447accessorsAndKVC/bk1ch10p447accessorsAndKVC/ViewController.swift

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class Dog : NSObject {
88

99
class DogOwner : NSObject {
1010
@objc var dogs = [Dog]()
11+
@objc var dog : Dog?
1112
}
1213

1314
//@objc protocol Named {
@@ -124,11 +125,31 @@ class ViewController: UIViewController {
124125
// no way; cannot substitute Swift keypath for a string
125126
// d.setValue("Rover", forKey:\Dog.name)
126127
// can of course use Swift
127-
d[keyPath:\Dog.name] = "Rover"
128+
d[keyPath:\.name] = "Rover"
128129
print(d.name)
130+
131+
let kp = String(describing:\Dog.name)
132+
print(kp)
133+
134+
let bgcolor = self[keyPath:\.view.backgroundColor]
135+
print("background color:", bgcolor as Any)
136+
137+
// this doesn't work
138+
// let path = #keyPath(CALayer.transform.rotation)
139+
140+
let layer = CALayer()
141+
layer.setValue("testing", forKey:"testing")
142+
let result = layer.value(forKey:"testing")
143+
print(result as Any) // testing
144+
// but you can't do that with #keyPath
145+
// layer[keyPath:\.testing] = "testing"
146+
129147

130148
let c = self.value(forKey:"hue") as? UIColor // "someone called the getter"
131-
print(c as Any) // Optional(UIDeviceRGBColorSpace 1 0 0 1)
149+
print("hue:", c as Any) // Optional(UIDeviceRGBColorSpace 1 0 0 1)
150+
151+
let c2 = self[keyPath:\.color] // _not_ \.hue
152+
print("color:", c2 as Any)
132153

133154
let myObject = MyClass()
134155
let arr = myObject.value(forKeyPath:"theData.name") as! [String]
@@ -165,9 +186,20 @@ class ViewController: UIViewController {
165186
let names = owner.value(forKeyPath:#keyPath(DogOwner.dogs.name)) as! [String] // ["Fido", "Rover"]
166187
let dog1name = dog1.value(forKey:#keyPath(Dog.name)) as! String
167188

168-
169189
print(names)
170190
print(dog1name)
191+
192+
do {
193+
let owner = DogOwner()
194+
let dog = Dog()
195+
dog.name = "Fido"
196+
owner.dog = dog
197+
if let name = owner.value(forKeyPath:"dog.name") as? String {
198+
print("keypath for dog name:", name)
199+
}
200+
}
201+
202+
171203
}
172204

173205

0 commit comments

Comments
 (0)