Swift-将字典[String:Any]编码和解码为plist [英] Swift - Encode and Decode a dictionary [String:Any] into plist

查看:351
本文介绍了Swift-将字典[String:Any]编码和解码为plist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典存储在我的类Marker中,但是抛出错误,指出该字典不可编码或无法解码.我可以看到错误是由[String:Any]引起的,但是我该如何解决呢?

I am trying to store the dictionary in my class Marker but it is throwing an error saying it is not encodable or decodable. I can see the error is caused by the [String: Any] but how can I go around it?

var buttonActions : [String: [String: [String:Any]]] = [:]

保存并加载

func saveData() {
    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")

    let encoder = PropertyListEncoder()
    do {
        let data = try encoder.encode(markerArray)
        try data.write(to: dataFilePath!)
        print("Saved")
    } catch {
        print("Error Encoding \(error)")
    }
}

func loadData() {
    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")

    if let data = try? Data(contentsOf: dataFilePath!){
        let decoder = PropertyListDecoder()
        do {
            markerArray = try decoder.decode([Marker].self, from: data)
        } catch {
            print("Decode Error \(error)")
        }
    }

班级

class Marker : Encodable, Decodable {
    var UUIDpic: UUID = UUID()
    var alpha: Int = 1
    var buttonType: Int = 0
    var buttonActions : [String: [String: [String:Any]]] = [:]
    var buttonNameColor: String = ""
    var buttonNameFontSize: Int = 10
    var buttonShape: String = ""
    var loggerRect: String = ""
    var maskColor: String = ""
    var name: String = ""
}

推荐答案

所以终于在Andrada的帮助下解决了这个问题.

So finally worked it out with the help of Andrada.

我添加了第二个结构来保存动作,并通过必须使用[string:any]

I added a second struct which held the action and by passed having to use [string:any]

class Marker : Encodable, Decodable {
var UUIDpic: UUID = UUID()
var alpha: Int = 1
var buttonType: Int = 0
var buttonAction : [String: [ButtonAction]] = [:] //Dictionary I edited using the new struct
var buttonNameColor: String = ""
var buttonNameFontSize: Int = 10
var buttonShape: String = ""
var loggerRect: String = ""
var maskColor: String = ""
var name: String = ""
}

下面是我添加的结构

struct ButtonAction: Codable {
var action: String
var array_linked_of_buttons: [[String:String]]

init(action: String, array_linked_of_buttons: [[String:String]]) {
 self.action = action
 self.array_linked_of_buttons = array_linked_of_buttons
    }
}

请确保初始化您的结构,否则它将无法正常工作.

Make sure to init your struct or it won't work.

这篇关于Swift-将字典[String:Any]编码和解码为plist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆