Assembling a data payload passed to GRMustache.swift for rendering mustache templates, I'm in a scenario where I need to append data to an array previously defined in the dictionary.
My data structure starts off as:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": [
// I need to append here later
]
]
The items
key pair is a collection I need to append later within a loop.
To add to the data["items"]
array, I'm trying something like:
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
data["items"].append(item)
}
This errors, as value of type Any?
has no member append
, and binary operator +=
cannot be applied to operands of type Any?
and [String : Any]
.
This makes sense, as I need to cast the value to append; however, I can't mutate the array.
Casting to array, whether forcing downcast gives the error:
(data["items"] as! Array).append(item)
'Any?' is not convertible to 'Array<_>'; did you mean to use 'as!' to force downcast?
Cannot use mutating member on immutable value of type 'Array<_>'
Seems like my cast is wrong; or, perhaps I'm going about this in the wrong way.
Any recommendation on how to fill data["items"]
iteratively over time?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…