方式一)遵循
NSCopying
系统协议
- 在自定义类中,实现该方法
func copy(with zone: NSZone? = nil) -> Any
- example
TestA
class TestA: NSCopying {
var name: String
init(name: String) { self.name = name }
func copy(with zone: NSZone? = nil) -> Any { TestA(name: name) }
}
方式二)遵循
Copying
自定义协议
- 在自定义类中,实现该方法
protocol Copying { init(obj: Self) }
- example
TestB
protocol Copying { init(obj: Self) }
extension Copying { var copy: Self { Self.init(obj: self) } }
class TestB: Copying {
var name: String
init(name: String) { self.name = name }
required init(obj: TestB) { self.name = obj.name }
}
方式三)遵循
Codable
系统协议
- 在自定义类中,遵循
Codable
协议 - 自定义一个遵循
Codable
协议的泛型方法
func copy<T: Codable>(_ obj: T) -> T?
- example
TestC
func codableCopy<T: Codable>(_ obj: T) -> T? {
do{
let jsonData = try JSONEncoder().encode(obj)
return try JSONDecoder().decode(T.self, from: jsonData)
}
catch {
print("Decode failed. \(error)"); return nil
}
}
class TestC: Codable {
var name: String
init(name: String) { self.name = name }
}
网友评论