Implementing copy() in Swift

前端 未结 10 1475
难免孤独
难免孤独 2020-11-27 15:31

I want to be able to copy a custom class in Swift. So far, so good. In Objective-C I just had to implement the NSCopying protocol, which means implementing

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 16:28

    Well, there is a really easy solution for this and you do not have to create root class.

    protocol Copyable {
        init(instance: Self)
    }
    
    extension Copyable {
        func copy() -> Self {
            return Self.init(instance: self)
        }
    }
    

    Now, if you want to make your custom class be able to copy, you have to conform it to Copyable protocol and provide init(instance: Self) implementation.

    class A: Copyable {
        var field = 0
    
        init() {
        }
    
        required init(instance: A) {
            self.field = instance.field
        }
    
    }
    

    Finally, you can use func copy() -> Self on any instance of A class to create a copy of it.

    let a = A()
    a.field = 1
    let b = a.copy()
    

提交回复
热议问题