Swift:从字符串中获取所有键值对

问题描述 投票:0回答:3

我有一个

String
,其中有许多键值对,并附加了
&
符号。即:
params = key1=Hello&key2=Hello World&key3=Hi Hello

有没有办法仅通过传递字符串中存在的键来提取值?例如我想提取key1,key2,key3的值。

ios swift3 alamofire
3个回答
3
投票
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
中,您将获得键值对。


1
投票

您可以通过创建虚拟 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)
}

另请参阅 解析 URL 字符串以获取键值的最佳方法?


0
投票
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")]
© www.soinside.com 2019 - 2024. All rights reserved.