Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify an object value in array using swift [duplicate]

Tags:

ios

swift

i am new to swift. I want to know how to modify an object in a for-each loop using swift. for example:

struct MyCustomObject { var customValue: String? }

let myArray: [MyCustomObject?]

for anObject:MyCustomObject in myArray {
    anObject.customValue = "Hello" // <---Cannot assign to property: 'anObject' is a 'let' constant 
}

so , what should I do if i want to change the object value in a for-loop. I tired adding "var" before anObject, but it doesnt work!! (the objects in the array still remain unchanged.)

For objective C , it is easy,

NSMutableArray * myArray = [NSMutableArray array];

for (MyCustomObject * object in myArray) 
{ 
  object.customValue = "Hello" 
}
like image 584
Noob IT Avatar asked Feb 24 '17 13:02

Noob IT


1 Answers

That's because values stored in an array are immutable. You have 2 options:

1: change MyCustomObject to a class:

class MyCustomObject { var customValue: String? }

2: iterate by index

for i in 0..<myArray.count {
    if myArray[i] != nil {
        myArray[i]!.customValue = "Hello"
    }
}
like image 198
Code Different Avatar answered Sep 22 '22 10:09

Code Different