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"
}
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With