如何在url字符串中编码''+'字符?

Rob*_*ert 2 url ios swift swift3

我想+在我的url字符串中编码字符,我试着这样做:

let urlString = "www.google.com?type=c++"

let result = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Run Code Online (Sandbox Code Playgroud)

但这不适用+.

任何的想法?谢谢.

更新:

type=url中的这个参数是动态的,我不会对+ 字符做一些隐含的替换.此type=参数表示UITextField值,因此可以键入任何内容.

我也很好奇为什么addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)不能在这种特殊情况下工作?

Vik*_*art 6

let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted

if let escapedString = "www.google.com?type=c++".addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
  print(escapedString)
}
Run Code Online (Sandbox Code Playgroud)

输出:

www.google.com%3Ftype%的3Dc%2B%2B