【发布时间】:2015-09-21 12:20:19
【问题描述】:
Objective-C 有一个setValue 方法,允许开发人员通过字段的名称为字段设置特定值。
如何在 Swift 中做到这一点而不从 NSObject 继承并实际使用 setValue 方法?
【问题讨论】:
Objective-C 有一个setValue 方法,允许开发人员通过字段的名称为字段设置特定值。
如何在 Swift 中做到这一点而不从 NSObject 继承并实际使用 setValue 方法?
【问题讨论】:
您可以使用 KVC 来执行此操作,afaik。 看看这个很酷的例子: 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
【讨论】: