Nisba
Nisba

Reputation: 3448

shouldn't `init(repeating:count)` be working by reference?

I tried this code in a playground:

var a = [String](repeating: String(), count: 2)
a[0] = "string"
a[1]

The last line prints the content of a[1] which is "".

Shouldn't it be "string", since I am passing a reference of an object to the constructor of the array a?

Does this mean that 2 objects of type String are created instead of just one repeated 2 times?

EDIT:

as pointed out by an user, the behaviour I was looking for is reproduced by the following code

import UIKit

class A {
    var str = "str"
}

var a = [A](repeating: A(), count: 2)
a[0].str = "a"
Swift.print(a[1].str) //this prints "a"

Upvotes: 0

Views: 42

Answers (1)

Sulthan
Sulthan

Reputation: 130102

First, you are not passing a reference. All strings are value types (not reference types). They are always copied.

Even if you passed a reference, it would be an initial value. Assigning a new reference to a[0] would not change the contents of the reference.

Too see the behavior for a reference, let's declare a real reference type:

class RefType {
    var value: String

    init(_ value: String) {
        self.value = value
    }
}

var a = [RefType](repeating: RefType("x"), count: 2)
// the same reference in both indices
print(a[0].value) //x
print(a[1].value) //x

// let's change the value of the reference
a[0].value = "y"
// still the same reference in both indices
print(a[0].value) //y
print(a[1].value) //y

// let's change one of the references to a new object
a[0] = RefType("z")
print(a[0].value) //z
print(a[1].value) //y

Upvotes: 2

Related Questions