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

查看:15
本文介绍了为什么 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?

文档说如果转换不可能",该方法返回 nil,但不清楚在什么情况下转义转换可能失败:

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.

我认为该方法可能对允许的字符集和用于转义的字符之间的不良交互应用了某种完整性检查,但事实并非如此:无论允许的字符集是否成功,该方法都会成功chars 包含%",如果允许的字符集为空也会成功.

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!

结果(出乎我的意料)可以成功创建包含未配对形式的无效 Unicode 的 Swift 字符串 UTF-16 代理字符.这样的字符串可能会导致 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: .utf16BigEndian)!

// Returns nil:
str.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

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

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