91

I want to store structs inside an array, access and change the values of the struct in a for loop.

struct testing {
    var value:Int
}

var test1 = testing(value: 6 )

test1.value = 2
// this works with no issue

var test2 = testing(value: 12 )

var testings = [ test1, test2 ]

for test in testings{
    test.value = 3
// here I get the error:"Can not assign to 'value' in 'test'"
}

If I change the struct to class it works. Can anyone tell me how I can change the value of the struct.

mfaani
  • 33,269
  • 19
  • 164
  • 293
reza23
  • 3,079
  • 2
  • 27
  • 42
  • Also see [value types vs class types](http://stackoverflow.com/a/41353620/5175709) Rob correctly says: *if you pass a value type as a parameter to a method that then does something on another thread, you're essentially working with a **copy** of that value type. This ensures the integrity of that object passed to the method.* – mfaani Jan 27 '17 at 18:32

9 Answers9

124

Besides what said by @MikeS, remember that structs are value types. So in the for loop:

for test in testings {

a copy of an array element is assigned to the test variable. Any change you make on it is restricted to the test variable, without doing any actual change to the array elements. It works for classes because they are reference types, hence the reference and not the value is copied to the test variable.

The proper way to do that is by using a for by index:

for index in 0..<testings.count {
    testings[index].value = 15
}

in this case you are accessing (and modifying) the actual struct element and not a copy of it.

Antonio
  • 71,651
  • 11
  • 148
  • 165
14

To simplify working with value types in arrays you could use following extension (Swift 3):

extension Array {
    mutating func modifyForEach(_ body: (_ index: Index, _ element: inout Element) -> ()) {
        for index in indices {
            modifyElement(atIndex: index) { body(index, &$0) }
        }
    }

    mutating func modifyElement(atIndex index: Index, _ modifyElement: (_ element: inout Element) -> ()) {
        var element = self[index]
        modifyElement(&element)
        self[index] = element
    }
}

Example usage:

testings.modifyElement(atIndex: 0) { $0.value = 99 }
testings.modifyForEach { $1.value *= 2 }
testings.modifyForEach { $1.value = $0 }
Anton Plebanovich
  • 1,296
  • 17
  • 17
13

Well I am going to update my answer for swift 3 compatibility.

When you are programming many you need to change some values of objects that are inside a collection. In this example we have an array of struct and given a condition we need to change the value of a specific object. This is a very common thing in any development day.

Instead of using an index to determine which object has to be modified I prefer to use an if condition, which IMHO is more common.

import Foundation

struct MyStruct: CustomDebugStringConvertible {
    var myValue:Int
    var debugDescription: String {
        return "struct is \(myValue)"
    }
}

let struct1 = MyStruct(myValue: 1)
let struct2 = MyStruct(myValue: 2)
let structArray = [struct1, struct2]

let newStructArray = structArray.map({ (myStruct) -> MyStruct in
    // You can check anything like:
    if myStruct.myValue == 1 {
        var modified = myStruct
        modified.myValue = 400
        return modified
    } else {
        return myStruct
    }
})

debugPrint(newStructArray)

Notice all the lets, this way of development is safer.

The classes are reference types, it's not needed to make a copy in order to change a value, like it happens with structs. Using the same example with classes:

class MyClass: CustomDebugStringConvertible {
    var myValue:Int

    init(myValue: Int){
        self.myValue = myValue
    }

    var debugDescription: String {
        return "class is \(myValue)"
    }
}

let class1 = MyClass(myValue: 1)
let class2 = MyClass(myValue: 2)
let classArray = [class1, class2]

let newClassArray = classArray.map({ (myClass) -> MyClass in
    // You can check anything like:
    if myClass.myValue == 1 {
        myClass.myValue = 400
    }
    return myClass
})

debugPrint(newClassArray)
LightMan
  • 3,517
  • 31
  • 31
  • Isn't doing your "map" purer? – Ian Warburton Oct 14 '16 at 18:53
  • @IanWarburton Sorry, but I don't understand that, what do you mean by "purer" ? – LightMan Oct 14 '16 at 20:27
  • I suppose it means more compliant with the functional programming paradigm. – Ian Warburton Oct 14 '16 at 22:45
  • So, immutability being a functional concept, surely it makes sense to go with a map? – Ian Warburton Oct 15 '16 at 13:11
  • 1
    Well this immutability has to do with how Swift works, in Swift structs are copied and class are passed by reference. So when you are changing a struct or passing it by argument you are making a new copy of it with the value changed. This has nothing to do with functional programming. Check the other answers, they all make copies of the array. Maps do the same thing and you can add conditions and new values while generating the new array. IMHO maps and the others are not exclusively used in functional programming, you can use them whenever you want. – LightMan Oct 25 '16 at 09:34
  • Passing by value is not the same as immutability. The question is specifically about not being able to mutate a value at all - not that they're changing a value in one place and it's not changing something elsewhere. – Ian Warburton Oct 25 '16 at 13:45
  • In Swift 3, the 'var' specifier is not allowed. In the map closure, you need to copy the given struct, set the new struct's values, then return the new struct. Tedious. – Womble Nov 04 '16 at 03:52
13

How to change Array of Structs

for every element:

itemsArray.indices.forEach { itemsArray[$0].someValue = newValue }

for specific element:

itemsArray.indices.filter { itemsArray[$0].propertyToCompare == true }
                  .forEach { itemsArray[$0].someValue = newValue }
Denis Rybkin
  • 471
  • 6
  • 7
4

You have enough of good answers. I'll just tackle the question from a more generic angle.

As another example to better understand value types and what it means they get copied:

struct Item {
    var value:Int

}

func change (item: Item, with value: Int){
    item.value = value //  cannot assign to property: 'item' is a 'let' constant
}

That is because item is copied, when it comes in, it is immutable — as a convenience.

Had you made Item a class type then you were able to change its value.


var item2 = item1 // mutable COPY created
item2.value = 10
print(item2.value) // 10
print(item1.value) // 5
mfaani
  • 33,269
  • 19
  • 164
  • 293
2

This is very tricky answer. I think, You should not do like this:

struct testing {
    var value:Int
}

var test1 = testing(value: 6)
var test2 = testing(value: 12)

var ary = [UnsafeMutablePointer<testing>].convertFromArrayLiteral(&test1, &test2)

for p in ary {
    p.memory.value = 3
}

if test1.value == test2.value {
    println("value: \(test1.value)")
}

For Xcode 6.1, array initialization will be

var ary = [UnsafeMutablePointer<testing>](arrayLiteral: &test1, &test2)
rintaro
  • 51,423
  • 14
  • 131
  • 139
2

It is possible to use the map function to get this effect - essentially creating a new array

itemsArray = itemsArray.map { 
  var card = $0
  card.isDefault = aCard.token == token
  return card
} 
Brian
  • 21
  • 2
0

I ended up recreating a new array of struct see the example below.

func updateDefaultCreditCard(token: String) {
    var updatedArray: [CreditCard] = []
    for aCard in self.creditcards {
        var card = aCard
        card.isDefault = aCard.token == token
        updatedArray.append(card)
    }
    self.creditcards = updatedArray
}
Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81
-1

I tried Antonio's answer which seemed quite logical but to my surprise it does not work. Exploring this further I tried the following:

struct testing {
    var value:Int
}

var test1 = testing(value: 6 )
var test2 = testing(value: 12 )

var testings = [ test1, test2 ]

var test1b = testings[0]
test1b.value = 13

// I would assume this is same as test1, but it is not test1.value is still 6

// even trying 

testings[0].value = 23

// still the value of test1 did not change.
// so I think the only way is to change the whole of test1

test1 = test1b
reza23
  • 3,079
  • 2
  • 27
  • 42
  • 13
    You are forgetting that every time you pass a value type around, you pass a copy of it, not a reference. So the results you have are expected. `testing` is initialized with a **copy** of `test1` and `test2`. Again, in `var test1b = testings[0]` you are creating a new copy of `testings[0]`, which is itself a copy of `test1` – Antonio Oct 15 '14 at 11:03