Reputation: 23
I am trying to set the value of a dictionary inside a array in swift but I get an error.
It says Cannot pass immutable value of type '[Dictionary]' to mutating binary operator '+='
My code is the following:
// Declare the array
var numbersArray:[Dictionary] = [Dictionary<String, Any>]()
... more code ...
func createArray() {
for var iteration = 0; iteration < 75; iteration++ {
//Add numbers to the array
// May be used to set column
var column:String
switch iteration {
case 0...14:
column = "B"
numbersArray += [["Randomized" : false, "Column" : "B", "Origin" : 0]]
case 15...29:
column = "I"
numbersArray += [["Randomized" : false, "Column" : "I", "Origin" : 0]]
case 30...44:
column = "N"
numbersArray += [["Randomized" : false, "Column" : "N", "Origin" : 0]]
case 45...59:
column = "G"
numbersArray += [["Randomized" : false, "Column" : "G", "Origin" : 0]]
case 60...74:
column = "O"
numbersArray += [["Randomized" : false, "Column" : "O", "Origin" : 0]]
default:
column = "Out Of Bounds"
numbersArray += [["Randomized" : false, "Column" : "Out Of Bounds", "Origin" : 0]]
}
// numbersArray1 += [["Randomized" : false, "Column" : String(column), "Origin" : 0]]
}
}
Any Idea?
Note: This worked perfectly in the playground.
Upvotes: 0
Views: 126
Reputation: 10136
I think there are 2 problems.
First of all, you declare numbersArray to be an array of generic dictionaries, which is something that makes my XCode to crash. The following approach works better for me:
var numbersArray = [[String: Any]]()
Secondly, I guess createArray is a method in a struct
, in which case you have to use mutating
in its declaration to allow it to modify struct
's properties.
mutating func createArray() {
// ...
}
Upvotes: 0
Reputation: 14845
You can't use += for arrays of not compatible items (where the type can change), you need append the value to the array like so:
var numbersArray = [Dictionary<String, Any>]()
numbersArray.append(["Randomized" : false, "Column" : "B", "Origin" : 0])
You would be able to use += if you had an array of Strings or Int's
var numbersArray = [String]()
NumbersArray += ["I am always a string"]
More details about collections at this apple documentation
Upvotes: 1