The signature of the String
method for percent-escaping is:
func addingPercentEncoding(withAllowedCharacters: CharacterSet)
-> String?
(This was stringByAddingPercentEncodingWithAllowedCharacters
in Swift 2.)
Why does this method return an optional?
The documentation says that the method returns nil “if the transformation is not possible,” but it's unclear under what circumstances the escaping transformation could fail:
Characters are escaped using UTF-8, which is a complete Unicode encoding. Any valid Unicode character can be encoded using UTF-8, and thus can be escaped.
I thought perhaps the method applied some kind of sanity check for bad interactions between the set of allowed chars and the chars used for escaping, but this is not the case: the method succeeds no matter whether the set of allowed chars contains "%", and also succeeds if the allowed char set is empty.
As it stands, the non-optional return value appear to be forcing a nonsensical error check.
str
in this answer is looks like "�" – Floro