swift - 将结构体属性名称作为参数传递,然后访问该属性

标签 swift accessor

我想编写一个为所有Equatable结构定义的部分比较函数,它能够比较两个结构实例,但忽略使用参数指定的任何属性。例如, unicorn 运算符 (🦄 ) 代表我缺少的内容:

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 ?

注意我不需要在运行时指定被忽略的属性 - 在此示例中,它们实际上可以在编译时知道。

注意2. 如果我需要将结构更改为类,那就这样吧,但我也不知道如何使用类来完成我需要的操作。

最佳答案

您可以将属性键路径传递给函数并像这样使用它们:

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)

关于swift - 将结构体属性名称作为参数传递,然后访问该属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270600/

相关文章:

swift - 无论我如何重新加载 UITableViewCell,它总是随机闪烁

xcode - ld : -bundle and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together

angularjs - 在 AngularJS Factory 中使用 Getter/Setter 方法

c# - 访问器的静态扩展

php - 如何在我的 Xcode 项目中显示和使用 php 文件?

ios - objectWillChange 不更新 View

ios - 在通过代码呈现的另一个 ViewController 上呈现 AlertController

ruby-on-rails - Rails ActiveRecord 存储中的动态属性

swift - Swift 类中的私有(private) Var

javascript - 动态属性访问器