"stringByAddingPercentEncodingWithAllowedCharacters" 替换了比应有的更多的字符

"stringByAddingPercentEncodingWithAllowedCharacters" replaces more characters than it should

玩 Swift 我遇到了一些我不明白的东西。

下面的代码不仅按预期替换了 /% 个字符,它还替换了 ä 个字符:

immport Foundation

extension String{
    func encode() -> String{
        let customAllowedSet =  NSCharacterSet(charactersInString:"/%").invertedSet
        return self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)!
    }
}

let testStr = "Ein String der % und / enthält"
// contains what is expected

let percentEncodedStr = testStr.encode()
// contains "Ein String der %25 und %2F enth%C3%A4lt"

let decodedStr = percentEncodedStr.stringByRemovingPercentEncoding
// contains what was in testStr originally 

为什么 ä%C3%A4 代替了?

该方法用于对 URL 的组件或子组件进行编码。 URL 中不允许使用非 ASCII 字符。它们总是被编码。

docs for stringByAddingPercentEncodingWithAllowedCharacters() 说:

Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.

也就是说,没有非 ASCII 字符被认为是 "allowed"。