How do I convert url.query to a dictionary in Swift?

前端 未结 6 1383
不知归路
不知归路 2021-02-09 02:06

I have a URL coming in to the AppDelegate method:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) ->         


        
6条回答
  •  灰色年华
    2021-02-09 02:24

    Here is an example using the Swift reduce function. This will turn a string like 'key1=value1&key2=value2&key3=value3' into a dictionary.

    let params = queryString.components(separatedBy: "&").map({
        $0.components(separatedBy: "=")
    }).reduce(into: [String:String]()) { dict, pair in
        if pair.count == 2 {
            dict[pair[0]] = pair[1]
        }
    }
    

提交回复
热议问题