Structify 旨在让你更轻松将 Swift 结构转换为 Objective-C 类,开发者无需手动将结构转换为类,反之亦然。
不使用 Structify
struct User { let address: String let company: String let email: String let name: String let phone: String let uid: String let username: String let website: String let birthday: Date } class RLMUser: Object { @objc dynamic var address: String = "" @objc dynamic var company: String = "" @objc dynamic var email: String = "" @objc dynamic var name: String = "" @objc dynamic var phone: String = "" @objc dynamic var uid: String = "" @objc dynamic var username: String = "" @objc dynamic var website: String = "" @objc dynamic var birthday: Date = Date() override class func primaryKey() -> String? { return "uid" } } extension RLMUser { func toStruct() -> User { return User(address: address, company: company, email: email, name: name, phone: phone, uid: uid, username: username, website: website, birthday: birthday) } } extension User { func toObject() -> RLMUser { return RLMUser.build { object in object.uid = uid object.address = address object.company = company object.email = email object.name = name object.phone = phone object.username = username object.website = website object.birthday = birthday } } }
乍一看似乎很方便的方法。但是如果你的结构不是那么小并且有更多的属性呢?如果你有太多类似User
这样的结构时怎么办?如果您想在开发过程中为现有结构添加更多属性怎么办?
使用 Structify
struct User { var address: String = "" var company: String = "" var email: String = "" var name: String = "" var phone: String = "" var uid: String = "" var username: String = "" var website: String = "" var birthday: Date = Date() } class RLMUser: Object { //you only set the primaryKey as usual override class func primaryKey() -> String? { return "uid" } } extension RLMUser: StructConvertible { typealias StructType = User } extension User: ObjectConvertible { typealias ClassType = RLMUser }
你唯一需要做的就是让你的结构符合
ObjectConvertible
协议并创建一个 Objective-C 对类并符合StructConvertible
协议。要求
- iOS 8.0+
- Xcode 10.+
- Swift 4.2+
安装
Structify 可通过 CocoaPods 获得。要安装它,只需将以下行添加到您的 Podfile 中:
pod 'Structify'
评论