Swift 实现 设所有发送或者接收到的数据为集合 M,将集合 M 内非空参数值的参数按照参数名 ASCII 码从小到大排序(字典序),如果参数值为对象,对象中的非空参数也需要按照参数名 ASC...

func stringWithDictionary(dict: NSDictionary ) -> String {

let allKeys = dict.allKeys
let sortKeys = allKeys.sorted { (a, b) -> Bool in
    let sa = a as! String
    let sb = b as! String
    return sa < sb
}
var resultString: String = ""
for tempKey in sortKeys {
    let key = tempKey as! String
    var tempValue = dict[key]
    
    if tempValue is NSDictionary {
        tempValue = stringWithDictionary(dict: tempValue as! NSDictionary)
    }
    
    let value = tempValue as! String
    
    resultString = resultString + "\(key)=\(value)&"
    
}
if resultString.count > 0 {
    resultString.removeLast()
}

print(" \(resultString)")

return resultString

}

使用
var loginParamDic:NSDictionary!
var jsonToStr:NSString!

loginParamDic = [
"cName":"bjq1","Acgloginpwd":"www","dpwd ":"piuq","AdAloginpwd ":"ynhq"]

jsonToStr = stringWithDictionary(dict: loginParamDic) as NSString
print("loginParamDic to & jsonToStr\n (jsonToStr)")
oginParamDic to & jsonToStr
Acgloginpwd=www&AdAloginpwd=1qaz1qa1&loginName=cq136&loginpwd =1qaz1qaz

你可能感兴趣的:(Swift 实现 设所有发送或者接收到的数据为集合 M,将集合 M 内非空参数值的参数按照参数名 ASCII 码从小到大排序(字典序),如果参数值为对象,对象中的非空参数也需要按照参数名 ASC...)