I'm writing a getter/setter for a class property that uses a struct. This is ultimately parsed from JSON and converted back to JSON in order to store data in the cloud.
// struct:
public struct CompletedTask {
var uuid: String!
var amount: Float?
}
// array of completed tasks on the class:
public var completedTasks: [CompletedTask] {
get {
var getValue: [CompletedTask] = []
if let _completedTasks = self["completedTasks"] as? [Dictionary<String, AnyObject>] {
_completedTasks.forEach({
getValue.append(CompletedTask(uuid: $0["uuid"], amount: nil))
})
}
return getValue
}
set(value) {
var setValue: [Dictionary<String, AnyObject>]
value.forEach({
if let amount = $0.amount where $0.amount != nil {
setValue.append(["uuid": $0.uuid, "amount": amount])
} else {
setValue.append(["uuid": $0.uuid])
}
})
self["completedTasks"] = setValue
}
}
The setter (I think, although I cannot test) is working fine (it compiles, anyway). But the getter is throwing:
Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'
What's going on? I think this is a simple fix, but I've tried several different options and it's not working.
First things first,
if let amount = $0.amount where $0.amount != nilis redundant, as the optional binding without the
whereclause guarantees that amount is not nil when theif letcondition is satisfied.As for that message, change
AnyObjecttoAny, asStringis aStructand not aClass.AnyObjectonly works with classes.More on
AnyvsAnyObjectcan be found here.