简体   繁体   中英

Swift 4 statically get value of model property name

When using Swift 3, I was defining my model like so

class Model: NSObject {
    var prop1: String
} 

When I wanted to access the static string value of the property name prop1, I would use let sad = #keyPath(Model.prop1) and it would give me "prop1" printed out. Happy days.

The problem is, that since upgrading to Swift 4, I am having trouble doing the above. I see in other posts that we can use the new \\Model.prop1 syntax but that seems to be providing the value of property rather than the string representation of the name.

I am also refactoring out the need for NSObject on my Swift models, but I would have thought I can still get this functionality.

Any help here would be appreciated!

Swift properties do not necessarily retain the strings of the property names at runtime. Therefore, if the Swift key path syntax were able to give you this string value, it would only be able to be used on NSObject -derived classes. The Swift key path syntax doesn't only work with those, though; it can also be used to refer to properties of non- @objc classes and structs. Therefore, this is not possible. The #keyPath syntax remains available, however, to get the string key path of an Objective-C property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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