Objective-C有一个setValue
方法,允许开发者通过名称设置特定字段的值。
在Swift中如何做到不继承自NSObject并实际使用setValue
方法呢?
Objective-C有一个setValue
方法,允许开发者通过名称设置特定字段的值。
在Swift中如何做到不继承自NSObject并实际使用setValue
方法呢?
据我所知,您可以使用KVC来实现此目的。看看这个很酷的例子:https://www.raywenderlich.com/163857/whats-new-swift-4
struct Lightsaber {
enum Color {
case blue, green, red
}
let color: Color
}
class ForceUser {
var name: String
var lightsaber: Lightsaber
var master: ForceUser?
init(name: String, lightsaber: Lightsaber, master: ForceUser? = nil) {
self.name = name
self.lightsaber = lightsaber
self.master = master
}
}
let sidious = ForceUser(name: "Darth Sidious", lightsaber: Lightsaber(color: .red))
let obiwan = ForceUser(name: "Obi-Wan Kenobi", lightsaber: Lightsaber(color: .blue))
let anakin = ForceUser(name: "Anakin Skywalker", lightsaber: Lightsaber(color: .blue), master: obiwan)
// Use keypath directly inline and to drill down to sub objects
let anakinSaberColor = anakin[keyPath: \ForceUser.lightsaber.color] // blue
// Access a property on the object returned by key path
let masterKeyPath = \ForceUser.master
let anakinMasterName = anakin[keyPath: masterKeyPath]?.name // "Obi-Wan Kenobi"
// AND HERE's YOUR ANSWER
// Change Anakin to the dark side using key path as a setter
anakin[keyPath: masterKeyPath] = sidious
anakin.master?.name // Darth Sidious