gpt4 book ai didi

swift - 有没有办法使用 value(forKeyPath :)? 访问 KVC 中的数组元素

转载 作者:行者123 更新时间:2023-11-30 11:05:50 25 4
gpt4 key购买 nike

假设我有一些类似于以下内容的 KVC 兼容对象:

class Person : NSObject {
var office: Office
var firstName: String
var lastName: String
var reports: [Report]

init( office: Office,
firstName: String,
lastName: String,
reports: [Report] ) {

...

}
}

class Office : NSObject {
var building: String
var room: Int

init( building: String,
room: Int ) {

...

}

}

class Report : NSObject {
var title: String
var contents: String

init( title: String,
contents: String ) {

...

}
}

我创建了一个实例,人

let person = Person(
office: Office(
building: "Main",
room: 2 ),
firstName: "Bob",
lastName: "Roberts",
reports: [
Report( title: "Today's weather", contents: "..." ),
Report( title: "Traffic", contents: "..." ),
Report( title: "Stocks", contents: "..." )
] )

我可以使用 person.value(forKeyPath:) 访问 person 的属性和嵌套属性,如下所示:

person.value(forKeyPath: "firstName") // "Bob"
person.value(forKeyPath: "office.room" ) // 2

但是,KVC 有办法从第二个报告中获取标题吗?

类似的东西

person.value(forKeyPath: "reports[1].title" ) // "Traffic"

最佳答案

即使使用结构,Swift 的原生 KVC 也是可能的,不需要 ObjC 运行时

struct Person {
var office: Office
var firstName: String
var lastName: String
var reports: [Report]
}

struct Office {
var building: String
var room: Int
}

struct Report {
var title: String
var contents: String
}

let person = Person(office: Office(building: "Main", room: 2 ),
firstName: "Bob", lastName: "Roberts",
reports: [
Report( title: "Today's weather", contents: "..." ),
Report( title: "Traffic", contents: "..." ),
Report( title: "Stocks", contents: "..." )
])


let keyPath = \Person.reports[1].title
let title = person[keyPath: keyPath] // "Traffic"

关于swift - 有没有办法使用 value(forKeyPath :)? 访问 KVC 中的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com