简体   繁体   English

Swift 2字典 <String, AnyObject> 构造getter / setter引发抛出不能下标值…索引类型为&#39;String&#39;的问题

[英]Swift 2 Dictionary<String, AnyObject> to Struct getter/setter throwing Cannot subscript value … with an index of type 'String'

I'm writing a getter/setter for a class property that uses a struct. 我正在为使用结构的类属性编写一个getter / setter。 This is ultimately parsed from JSON and converted back to JSON in order to store data in the cloud. 最终,它会从JSON中解析出来并转换回JSON,以便将数据存储在云中。

// 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. 我认为这是一个简单的修复程序,但是我尝试了几种不同的选择,但没有用。

Sorry to say this, but your code is completely wrong. 抱歉,您的代码是完全错误的。

It's worthy to note that this code did not compile for me. 值得注意的是这段代码不是为我编译的。 I'm using Swift 2.0 and xcode 7.2. 我正在使用Swift 2.0和xcode 7.2。 In addition, there are a few things I'd like to point out. 另外,我想指出几件事。

  1. You shouldn't be writing to your computed property. 您不应该写入您的计算属性。 Look into stored properties instead. 而是查看存储的属性。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID259 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID259

  2. Unless you're extending a dictionary, you can't subscript properties of a class. 除非您要扩展字典,否则不能对类的属性进行下标。 To access a class's properties within a closure use self.completedTask. 要在闭包内访问类的属性,请使用self.completedTask。

  3. You can't simply cast a collection of a type you created to a collection of dictionaries. 您不能简单地将创建的类型的集合转换为字典的集合。

  4. I don't actually see anything converted to JSON. 我实际上看不到任何转换为​​JSON的内容。 I assume you did this somewhere else in the code. 我假设您在代码中的其他位置执行了此操作。

Under the assumption that you wanted to created a computed property that saves a list of CompletedTasks as a Dictionary and returns a list of CompletedTask objects.. 在您要创建一个计算属性的假设下,该属性将CompletedTasks的列表另存为Dictionary,并返回CompletedTask对象的列表。

public struct CompletedTask {
    var uuid: String!
    var amount: Float?
}

private var tasks : [[String: AnyObject?]] = []

var completedTasks: [CompletedTask] {
    get {
        var _cT : [CompletedTask] = []

        tasks.forEach({
            _cT.append(CompletedTask(uuid: $0["uuid"] as! String, amount: $0["amount"] as? Float))
        })

        return _cT
    }
    set (value) {
        var _t : [[String: AnyObject?]] = []

        value.forEach({
            _t.append(["uuid": $0.uuid, "amount": $0.amount])
        })

        tasks = _t
    }
}
let task_1 = CompletedTask(uuid: "1", amount: nil)
let task_2 = CompletedTask(uuid: "2", amount: nil)
completedTasks = [task_1, task_2]
print("Completed Tasks \(completedTasks)")

First things first, 首先,

if let amount = $0.amount where $0.amount != nil

is redundant, as the optional binding without the where clause guarantees that amount is not nil when the if let condition is satisfied. 是多余的,因为不带where子句的可选绑定保证了满足if let条件时,金额不为nil。

As for that message, change AnyObject to Any , as String is a Struct and not a Class . 对于该消息,将AnyObject更改为Any ,因为StringStruct而不是Class AnyObject only works with classes. AnyObject仅适用于类。

More on Any vs AnyObject can be found here . 有关Any vs AnyObject更多信息,请参见此处

The error was simply due to the fact that I wasn't casting my types in the getter: 该错误仅是由于我没有在getter中强制转换我的类型:

getValue.append(CompletedTask(uuid: $0["uuid"], amount: nil))

Should have been: 本来应该:

getValue.append(CompletedTask(uuid: $0["uuid"] as? String, amount: nil))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 迅速:无法下标[字典式]的值 <String, AnyObject> ],其索引类型为字符串 - swift: cannot subscript a value of type [Dictionary<String, AnyObject>] with an index of type string 无法下标[AnyObject]的值? 索引类型为String - Cannot subscript a value of [AnyObject]? with an index of type String 无法使用索引类型为“String”的类型&#39;[String:AnyObject]&#39;下标值 - Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String' 无法用索引类型“ String”下标“ [String:AnyObject]”类型的值 - Cannot subscript a value of type '[String: AnyObject]' with an index of type 'String' 无法使用索引类型为“字符串”的下标“ [[String:AnyObject]]”的值 - Cannot subscript a value of type '[[String : AnyObject]]' with an index of type 'String' 不能下标类型为[String:AnyObject]的值?索引类型为String - Cannot subscript a value of type [String: AnyObject]? with an index of type String “无法下标‘字典’类型的值<nsobject, anyobject> ' 索引类型为 'String' 错误</nsobject,> - "Cannot subscript a value of type 'Dictionary<NSObject, AnyObject>' with an index of type 'String" error 错误无法下标“字典”类型的值 <NSObject, AnyObject> &#39;的索引类型为&#39;String&#39; - Error Cannot subscript a value of type 'Dictionary<NSObject, AnyObject>' with an index of type 'String' 不能下标'[NSObject:AnyObject]类型的值吗?索引类型为'String' - Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String' 无法用索引类型“字符串”下标“ [NSObject:AnyObject]”类型的值 - Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM