Swift:如何将[String:Any]数组转换为特定数组

时间:2018-07-08 10:55:10

标签: ios arrays swift casting

我有这个简单的Struct:

protocol DocumentSerializable {
    init?(dictionary:[String:Any])
}

struct Item {
    var title:String
    var text:String?
    var dictionary:[String:Any] {
        return [
            "title":title,
            "text":text,
        ]
    }
}

extension Item : DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard let title = dictionary["title"] as? String,
            let text = dictionary["text"] as? String? else {return nil}

        self.init(title: title, text: text)
    }
}

当我获取json时,我将其放入数组中...

if let array = result?.data as? Array<[String:Any]> {...

如何将该数组转换为Items数组? var itemsArray = [Item]()

两个数组的结构完全相同

谢谢

2 个答案:

答案 0 :(得分:2)

使用

struct Item :Decodable {
 let title:String
 let text:String?
}

//

do {

    let root = try JSONDecoder().decode([Item].self, from:jsonData)

    print(root)

}
catch {

    print(error)
}

答案 1 :(得分:1)

使用compactMap,它也可以处理nil情况:

itemsArray = array.compactMap{ Item(dictionary: $0) }

但是,在Swift 4中,强烈建议使用Codable协议