How do I make a exact duplicate copy of an array?

前端 未结 5 1449
一向
一向 2020-11-27 13:24

How would I make an exact duplicate of an array?

I am having hard time finding information about duplicating an array in Swift.

I tried using .copy()

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 13:54

    For normal objects what can be done is to implement a protocol that supports copying, and make the object class implements this protocol like this:

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

    And then the Array extension for cloning:

    extension Array where Element: Copying {
        func clone() -> Array {
            var copiedArray = Array()
            for element in self {
                copiedArray.append(element.copy())
            }
            return copiedArray
        }
    }
    

    and that is pretty much it, to view code and a sample check this gist

提交回复
热议问题