如何将带有Array的Dictionary转换为String并返回?

时间:2017-11-29 16:14:09

标签: arrays swift dictionary

如何将带数组的Dictionary转换为字符串并返回?

.exec( (error, employee) => { console.log(employee) }

我可以使用JSON吗?

2 个答案:

答案 0 :(得分:0)

对字符串稍作调整,因为字典键(http://www.somehost.com)包含您尝试使用的分隔符(:),因此它会使解码变得相当繁琐。

由于将Dictionary映射到(key, value)元组很容易,因此编码功能非常简单:

func encode(_ entry: (key: String, value: [String]), keySeparator: String, arraySeparator: String) -> String
{
    return entry.key + keySeparator + encode(entry.value, separator: arraySeparator)
}

func encode(_ array: [String], separator: String) -> String
{
    return array.joined(separator: separator)
}

然后可以简单地解码:

func decode(_ strings: [String], keySeparator: String, arraySeparator: String) -> [String:[String]]
{
    return strings.reduce([String:[String]]())
    {
        var dict = $0
        guard let decoded = decode($1, keySeparator: keySeparator, arraySeparator: arraySeparator)
            else { return $0 }

        dict[decoded.key] = decoded.value
        return dict
    }
}

func decode(_ string: String, keySeparator: String, arraySeparator: String) -> (key: String, value: [String])?
{
    let split = string.components(separatedBy: keySeparator)

    guard split.count == 2 else { return nil }

    let key = split[0]
    let value = decodeValues(split[1], separator: arraySeparator)
    return (key, value)
}

func decodeValues(_ string: String, separator: String) -> [String]
{
    return string.components(separatedBy: separator)
}

最后,运行一切都可以通过以下方式完成:

let dict = ["http://www.somehost.com":
    [
        "some_name",
        "some_pass",
        "date_modification",
        "other_stuff"
    ]
]

let keySeparator = "::"
let arraySeparator = " / "

let encoded = dict.map { encode($0, keySeparator: keySeparator, arraySeparator: arraySeparator) }
print(encoded) // ["http://www.somehost.com::some_name / some_pass / date_modification / other_stuff"]

let decoded = decode(encoded, keySeparator: keySeparator, arraySeparator: arraySeparator)
print (decoded) // ["http://www.somehost.com": ["some_name", "some_pass", "date_modification", "other_stuff"]]

这个明确的内容可以通过扩展来加以解决,但这将使你获得80%的支持。

答案 1 :(得分:0)

您应该使用名为JSONSerialization的{​​{1}}方法将字典转换为Data data(withJSONObject:)方法,将其转换回字典:尝试实现自己的编码对于已经完成的事情的解码方法是没有意义的。试试这样:

JSONSerialization
jsonObject(with:)