Swift - 字典 拼接成 URL字符串

将字典中的键值对按照一定顺序拼接成到get 请求的参数中

var signParmeters : [String:Any] = [

    "client_id" : 67,

    "idfa" : "lfgoebiehfhfihdilh",

    "sn" : "khceilwgcidwlgcbdlwvc",

    "timestamp" : 12345678,

    "url" : "lgksjhdgdwcldwcvldvcdilvdk",

    "version" : 1.50

]

//排序 - 根据字典 key 首字母

let arr = signParmeters.sorted{ (t1, t2) -> Bool in

    return t1.0 < t2.0

}

//变形 - “k=v”

let strArr = arr.map{ (k:String,v:Any) -> String in

    return String(format:"%@=%@",k,String(describing: v))

}

//拼接 - “k1=v1&k2=v2&k3=v3...”

let str = strArr.joined(separator:"&")

print(str)

你可能感兴趣的:(Swift - 字典 拼接成 URL字符串)