Why is the return value of String.addingPercentEncoding() optional?

后端 未结 2 941
醉话见心
醉话见心 2020-12-03 07:11

The signature of the String method for percent-escaping is:

func addingPercentEncoding(withAllowedCharacters: CharacterSet)
    -> String?
         


        
2条回答
  •  不知归路
    2020-12-03 07:24

    I filed a bug report with Apple about this, and heard back — with a very helpful response, no less!

    Turns out (much to my surprise) that it’s possible to successfully create Swift strings that contain invalid Unicode in the form of unpaired UTF-16 surrogate chars. Such a string can cause UTF-8 encoding to fail. Here’s some code that illustrates this behavior:

    // Succeeds (wat?!):
    let str = String(
        bytes: [0xD8, 0x00] as [UInt8],
        encoding: String.Encoding.utf16BigEndian)!
    
    // Returns nil:
    str.addingPercentEncoding(withAllowedCharacters:
        CharacterSet.alphanumerics)
    

提交回复
热议问题