如何将字典键和值(字符串/数组)映射到swift中的一个字符串

时间:2017-07-12 16:21:31

标签: arrays dictionary swift3

我有一本看起来像的字典:

["foo": "whatever", "this": "that", "category": ["cat1", "cat2"]]

我需要它像一个字符串:

foo=whatever&this=that&category=cat1&category=cat2

因此,如果某个键的值为array类型,则该键应在字符串中多次出现。

2 个答案:

答案 0 :(得分:2)

正如亚历山大所说,这是一个URLComponentsURLQueryItem

的解决方案
import Foundation

let dict: [String: Any] = [
    "foo": "whatever",
    "this": "that",
    "category": [
        "cat1",
        "cat2"
    ]
]

var queryItems = [URLQueryItem]()
for (key, value) in dict {
    if let strings = value as? [String] {
        queryItems.append(contentsOf: strings.map{ URLQueryItem(name: key, value: $0) })
    } else {
        queryItems.append(URLQueryItem(name: key, value: value as? String))
    }
}

var urlComponents = URLComponents(string: "http://myserver.com")!
urlComponents.queryItems = queryItems
let url = urlComponents.url!
print(url.absoluteString) // => http://myserver.com?this=that&foo=whatever&category=cat1&category=cat2

类似的解决方案,但更简单,使用flatMap

let queryItems = dict.flatMap { key, value -> [URLQueryItem] in
    if let strings = value as? [String] {
        return strings.map{ URLQueryItem(name: key, value: $0) }
    } else {
        return [URLQueryItem(name: key, value: value as? String)]
    }
}

var urlComponents = URLComponents(string: "http://myserver.com")!
urlComponents.queryItems = queryItems
let url = urlComponents.url!
print(url.absoluteString) // => http://myserver.com?this=that&foo=whatever&category=cat1&category=cat2

答案 1 :(得分:0)

如果你知道你的字典类型,我相信这样的事情应该有用:

var string = ""
for key in dict.keys {
    if let array = dict[key] as? [String] {
        for arrayItem in array {
            string += "\(key)=\(arrayItem)&"
        }
    }
    else if let value = dict[key] as? String {
        string += "\(key)=\(value)&"
    }
}

print(string.substring(to: string.index(before: string.endIndex)))

注意这可能会以随机顺序打印它们,因为字典没有排序