使用 Codegen 实现类 Kotlin 复制功能的 Swift 包
SwiftCopy
一个 Swift 包,提供一种方便的、类似 Kotlin 的方式来复制 Swift 类型如 struct
的不可变实例。
用法
只需让你的结构体符合 Copyable
协议。
struct User: Copyable {
let id: Int
let firstName: String
let lastName: String
let created: Date
}
let myUser = User(id: "123", firstName: "David", lastName: "Scheutz", created = .now)
// Copy the instance by changing the `firstName` and `lastName` properties
let updatedUser = myUser.copy(firstName: "Your", lastName: "Name")
可选属性支持
SwiftCopy
使用 OptionalCopy
枚举包装可选属性,提供对如何更新或重置其状态的显式控制。
public enum OptionalCopy<T> {
case update(T)
case reset
case noChange // default value used by the copy function
}
struct User: Copyable {
let id: Int
let name: String
let profilePicture: String?
}
let myUser = User(id: "123", name: "David", profilePicture: nil)
// Copy the instance by setting the `profilePicture`
_ = myUser.copy(profilePicture: .update("https://dave.com/pictures/214381"))
// Copy the instance by resetting the `profilePicture`
_ = myUser.copy(profilePicture: .reset)
// Copy the instance by using an optional type directly
let optionalValue: String? = "Value"
_ = myUser.copy(profilePicture: .use(optionalValue))