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

前端 未结 5 1416
一向
一向 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<Element>()
            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

    0 讨论(0)
  • 2020-11-27 14:09

    Nate is correct. If you are working with primitive arrays all you need to do is assign duplicateArray to the originalArray.

    For the sake of completeness, if you were working an NSArray object, you would do the following to do a full copy of an NSArray:

    var originalArray = [1, 2, 3, 4] as NSArray
    
    var duplicateArray = NSArray(array:originalArray, copyItems: true)
    
    0 讨论(0)
  • 2020-11-27 14:12

    There is a third option to Nate's answer:

    let z = x.map { $0 }  // different array with same objects
    

    * EDITED * edit starts here

    Above is essentially the same as below and actually using the equality operator below will perform better since the array won't be copied unless it is changed (this is by design).

    let z = x
    

    Read more here: https://developer.apple.com/swift/blog/?id=10

    * EDITED * edit ends here

    adding or removing to this array won't affect the original array. However, changing any of the objects' any properties that the array holds would be seen in the original array. Because the objects in the array are not copies (assuming the array hold objects, not primitive numbers).

    0 讨论(0)
  • 2020-11-27 14:13

    Arrays have full value semantics in Swift, so there's no need for anything fancy.

    var duplicateArray = originalArray is all you need.


    If the contents of your array are a reference type, then yes, this will only copy the pointers to your objects. To perform a deep copy of the contents, you would instead use map and perform a copy of each instance. For Foundation classes that conform to the NSCopying protocol, you can use the copy() method:

    let x = [NSMutableArray(), NSMutableArray(), NSMutableArray()]
    let y = x
    let z = x.map { $0.copy() }
    
    x[0] === y[0]   // true
    x[0] === z[0]   // false
    

    Note that there are pitfalls here that Swift's value semantics are working to protect you from—for example, since NSArray represents an immutable array, its copy method just returns a reference to itself, so the test above would yield unexpected results.

    0 讨论(0)
  • 2020-11-27 14:15

    If you want to copy the items of an array of some class object. Then you can follow the below code without using NSCopying protocol but you need to have an init method which should take all the parameters that are required for your object. Here is the code for an example to test on playground.

    class ABC {
        
        var a = 0
        func myCopy() -> ABC {
            
            return ABC(value: self.a)
        }
        
        init(value: Int) {
            
            self.a = value
        }
    }
    
    var arrayA: [ABC] = [ABC(value: 1)]
    var arrayB: [ABC] = arrayA.map { $0.myCopy() }
    
    arrayB.first?.a = 2
    print(arrayA.first?.a)//Prints 1
    print(arrayB.first?.a)//Prints 2
    
    0 讨论(0)
提交回复
热议问题