Search code examples
arraysswiftswift3

Update individual item in the array swift


I have an array like this. How do I update the individual var when I update the array?

var value1 = 1
var value2 = 2
var value3 = 3

var array = [value1, value2, value3]
array[0] = 0

This will update the value in the array but will not update var value1. How do I update var value1 when I update the array without having to do value1 = 0?


Solution

  • As jnpdx said, Int is a value type. The behavior you describe requires “reference semantics”. If you want that behavior, you could theoretically introduce a class reference type, e.g.:

    class Foo: ExpressibleByIntegerLiteral {
        var value: Int
        
        required init(integerLiteral value: IntegerLiteralType) {
            self.value = value
        }
    }
    
    let foo1: Foo = 1
    let foo2: Foo = 2
    let foo3: Foo = 3
    
    let array = [foo1, foo2, foo3]
    array[0].value = 42                  // not `array[0] = 42`, which would attempt to replace the `Foo` instance at index 0 with a new instance separate from `foo1`
    
    print(foo1.value)                    // 42
    

    In this case, I have replace the array of Int value types with an array of Foo reference types.


    The above notwithstanding, we would generally use that pattern sparingly, as we now generally avoid reference types, favoring value types wherever possible. This helps avoid problems stemming from unintended sharing. See WWDC 2015’s Protocol-Oriented Programming in Swift video.