简体   繁体   English

Swift 4中键值编码的优点

[英]Advantage of Key-Value Coding in 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). 我只是想知道Swift 4中键值编码的好处。因为我很清楚键值编码(保持对属性的引用而不实际访问属性所持有的底层数据)。

For Example: 例如:

struct Student {
    var name: String?
    var rollNo: String?
}

let student = Student(name: "aman", rollNo: "12121")
let nameKey = \Student.name
let name = student[keyPath: nameKey]

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 . 这里我们创建了Student的实例并通过下标(keyPath)访问值,但我可以通过编写代码student.name轻松访问该值。

In Objective-C, we use string as a key like given below and we could take some benefits from it 在Objective-C中,我们使用字符串作为下面给出的键,我们可以从中获益

 [object valueForKey:@"name"]

My question is that is there any benefits related to coding level or memory level? 我的问题是,编码级别或内存级别是否有任何好处?

Two key advantages are: 两个主要优点是:

  1. Keys are validated: Xcode will warn you, at compile time, if you try to use a key that is not valid. 验证密钥:如果您尝试使用无效密钥,Xcode将在编译时向您发出警告。

  2. Results are strongly typed: With the following, the compiler will know that the resulting name is a String : 结果是强类型的:通过以下内容,编译器将知道结果nameString

     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. 结果是编写安全代码要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM