简体   繁体   English

Swift [String:AnyObject]无法转换为T Swift数组

[英]Swift[String: AnyObject] not convertible to T Swift Arrays

I am working inside a Swift Extension. 我正在使用Swift扩展程序。 I am trying to append data to an array of the type [[String: AnyObject]] . 我试图将数据追加到[[String: AnyObject]]类型的数组中。 The reason that this is in an extension is because I have to do this lot's of times to lot's of arrays. 之所以在扩展中,是因为我必须对很多数组进行很多次。 The problem is, when I append an object of type: [String: AnyObject] , I get the error: Dictionary'<'String, AnyObject'>' Not Convertible to T (the quotes are there because within the carrots nothing showed up). 问题是,当我追加类型为[String: AnyObject]的对象时,出现错误: Dictionary'<'String, AnyObject'>' Not Convertible to T (引号存在,因为在胡萝卜中未显示任何内容) 。

mutating func appendData(data: [String: [String: AnyObject]]?) {
    if data != nil {
        for (id, object) in data! {
            var mutatingObject = object
            mutatingObject["id"] = id
            append(mutatingObject)
        }
    }
}

I am not certain what exactly are you trying to achieve. 我不确定您到底要达到什么目标。 but take a note - Arrays are generic collections that store specific type. 但请注意-数组是存储特定类型的通用集合。 Extension for Array might not know what type will be used in each case, so it cannot simply allow you to store Dictionary<String, AnyObject> . Array扩展可能不知道在每种情况下将使用哪种类型,因此它不能简单地允许您存储Dictionary<String, AnyObject>

Here is an example on how to make your code more generic: 这是有关如何使代码更通用的示例:

extension Array {
    mutating func appendData(data: [String: T]?) {
        if data != nil {
            for (id, object) in data! {
                if var mutatingObject = object as? [String : AnyObject] {
                    mutatingObject["id"] = id
                }

                append(object)
            }
        }
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM