diatrevolo diatrevolo - 1 year ago 102
Swift Question

If var seems to deep copy arrays in Swift. Does if let?

In Swift 3.0, the code below gives different addresses for

, suggesting that the array was deep copied. Is this actually the case, or am I missing something in my analysis? Does if let behave the same way? It may be irrelevant for if let, as it is immutable...

var thisArray: [String]? = ["One", "Two"]
withUnsafePointer(to: &thisArray![0]) {
print("thisArray[0] has address \($0)")
if var thisArray = thisArray {
withUnsafePointer(to: &thisArray[0]) {
print("thisArray[0] has address \($0)")

Answer Source

Relevant: https://developer.apple.com/swift/blog/?id=10.

In Swift, Array, String, and Dictionary are all value types.

So, if you assign an existing value type via var or let then a copy occurs. If you assign an existing reference type (such as a class) via var or let then you'll be assigning a reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download