Playing around with Swift I came across something I do not understand.
The following code replaces not only the /%
characters as intended, it also replaces the ä
character:
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
Why is the ä
replaced by %C3%A4
?
That method is for encoding components or subcomponents of URLs. No non-ASCII characters are ever allowed in URLs. They are always encoded.
The docs for
stringByAddingPercentEncodingWithAllowedCharacters()
say:That is, no non-ASCII characters are ever considered to be "allowed".