Structify将 Swift 结构转换为 Objc 类的工具

联合创作 · 2023-10-02 05:42

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'

 

浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报