将结构属性名称作为参数传递,然后访问该属性
问题描述:
我想要编写一个部分比较函数,它定义了所有Equatable
结构体,它们能够比较两个结构体实例,但忽略使用参数指定的任何属性。例如,在麒麟运营商(
)代表什么我失踪:将结构属性名称作为参数传递,然后访问该属性
struct Struct1: Equatable {
x: Int
y: Int
z: Int
}
func compare<T: Equatable>(_ a: T, _ b: T, ignoring ignoredProperties: [Property]) { // N.B. “Property” is a made-up type.
var alteredA = a
for property in ignoredProperties {
alteredA property = b property
}
return alteredA == b
}
let s1 = Struct1(x:1, y:2, z:3)
let s2 = Struct1(x:1, y:2, z:4) // s2 is the same as s1, except for the value of property “z”
compare(s1, s2, ignoring: []) // -> false
compare(s1, s2, ignoring: [Property(Struct1.z)]) // -> true
我可以用它代替
和Property
什么?
N.B.我不需要在运行时指定被忽略的属性 - 在本例中,它们实际上可以在编译时知道。
N.B. 2.如果我需要将我的结构变成一个类,那就这样吧,但是我真的不知道如何用类来做我需要的东西。
答
你可以通过属性keypaths的功能,并使用它们像这样:
class Person: NSObject {
dynamic var firstName: String = ""
dynamic var lastName: String = ""
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
func setProperty<T: NSObject>(object: T, path: String, value: Any) {
object.setValue(value, forKey: path)
}
let firstNamePath = #keyPath(Person.firstName)
let chris = Person(firstName: "chris", lastName: "jones")
setProperty(object: chris, path: firstNamePath, value: "notChrisAnyMore")
print(chris.firstName)
好。如果没有人提出一种坚持结构的方法,那将是被接受的答案。 –
我不认为它可以用一个结构来完成,可能是错误的:) – simonWasHere