我有一个
String
,其中有许多键值对,并附加了 &
符号。即:params = key1=Hello&key2=Hello World&key3=Hi Hello
有没有办法仅通过传递字符串中存在的键来提取值?例如我想提取key1,key2,key3的值。
let string = "key1=Hello&key2=Hello World&key3=Hi Hello"
let components = string.components(separatedBy: "&")
var dictionary: [String : String] = [:]
for component in components{
let pair = component.components(separatedBy: "=")
dictionary[pair[0]] = pair[1]
}
在
dictionary
中,您将获得键值对。
您可以通过创建虚拟 URL 来使用
URLComponents
和 URLQueryItem
let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
if let components = URLComponents(string: "http://dummy.com/path?" + params.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!),
let queryItems = components.queryItems {
let arrayOfValues = queryItems.flatMap{ $0.value }
print(arrayOfValues)
}
let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
let separated = params.components(separatedBy: CharacterSet(charactersIn: "&="))
let keys = separated.enumerated().filter{$0.0 % 2 == 0}
print (keys) // [(offset: 0, element: "key1"), (offset: 2, element: "key2"), (offset: 4, element: "key3")]