Swift 4 中键值编码的优势 [英] Advantage of Key-Value Coding in Swift 4
问题描述
我只想知道 Swift 4 中键值编码的好处.因为我很清楚键值编码(保留对属性的引用,而不实际访问该属性所持有的基础数据).
I just want to know the benefits of Key-Value Coding in Swift 4. As I am well aware of key-value coding (hold reference to properties without actually accessing the underlying data held by the property).
例如:
struct Student {
var name: String?
var rollNo: String?
}
let student = Student(name: "aman", rollNo: "12121")
let nameKey = \Student.name
let name = student[keyPath: nameKey]
这里我们创建了Student的实例并通过下标(keyPath)访问值,但我可以通过简单地编写代码student.name
轻松访问该值.
Here we created the the instance of Student and access the value by subscript (keyPath) but I can easily access the value by simply writing the code student.name
.
在 Objective-C 中,我们使用字符串作为键,如下所示,我们可以从中受益
In Objective-C, we use string as a key like given below and we could take some benefits from it
[object valueForKey:@"name"]
我的问题是编码级别或内存级别有什么好处吗?
My question is that is there any benefits related to coding level or memory level?
推荐答案
两个主要优势是:
已验证密钥:如果您尝试使用无效的密钥,Xcode 会在编译时警告您.
Keys are validated: Xcode will warn you, at compile time, if you try to use a key that is not valid.
结果是强类型的: 使用以下内容,编译器将知道结果 name
是一个 String
:>
Results are strongly typed: With the following, the compiler will know that the resulting name
is a String
:
let name = student[keyPath: nameKey]
这消除了进行任何转换的需要.
This eliminates the need to do any casting.
结果是编写安全代码要容易得多.
The result is that it's much easier to write safe code.
这篇关于Swift 4 中键值编码的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!