为什么String.addingPercentEncoding()的返回值是可选的? [英] Why is the return value of String.addingPercentEncoding() optional?

查看:371
本文介绍了为什么String.addingPercentEncoding()的返回值是可选的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

百分比转义的 String 方法的签名为:

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

func addingPercentEncoding(withAllowedCharacters: CharacterSet)
    -> String?

(这是Swift 2中的 stringByAddingPercentEncodingWithAllowedCharacters

(This was stringByAddingPercentEncodingWithAllowedCharacters in Swift 2.)

为什么这个方法返回一个可选的?

Why does this method return an optional?

文档说方法返回nilif转换是不可能的,但不清楚在什么情况下转义转换可能失败:

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:


  • 字符使用UTF-8 ,这是一个完整的Unicode编码。任何有效的Unicode字符都可以使用UTF-8进行编码,因此可以进行转义。

  • 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.

推荐答案

我向Apple提交了一个关于这个问题的错误报告,听到了 - 一个非常有帮助的回应,不会少!

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

(非常惊讶的是)有可能成功创建包含无效的UTF-16代理字符形式的无效Unicode的Swift字符串。这样的字符串可能导致UTF-8编码失败。下面是一些说明这种行为的代码:

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)

这篇关于为什么String.addingPercentEncoding()的返回值是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆