NSURL 失败初始化程序 initWithString:Swift 中的空字符串不会 return nil
NSURL fail able initialiser initWithString: does not return nil on empty String in Swift
在 Playground 中很容易重现
import Foundation
let urlString = ""
let url = NSURL(string: urlString)
print(url)
url 的结果不知何故 (no URL)
而不是预期的 nil
并且打印输出是 Optional()
,既没有 .Some
也没有 .None
。
我真的很想对这个有一些了解,因为它让我大吃一惊并导致生产代码崩溃。
找出答案的最佳方法是阅读文档
convenience init?(string URLString: String)
Return Value
An NSURL object initialized with URLString. If the URL string was malformed, returns nil.
Discussion
This method expects URLString to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding.
所以你必须检查 nil
在我为此填写雷达后,我得到了以下答案:
Apple Developer Relations
An empty string is a valid URL string. It has no scheme, no authority (user/password/host/port), an empty path, no query and no fragment.
所以它似乎按预期工作。
在 Playground 中很容易重现
import Foundation
let urlString = ""
let url = NSURL(string: urlString)
print(url)
url 的结果不知何故 (no URL)
而不是预期的 nil
并且打印输出是 Optional()
,既没有 .Some
也没有 .None
。
我真的很想对这个有一些了解,因为它让我大吃一惊并导致生产代码崩溃。
找出答案的最佳方法是阅读文档
convenience init?(string URLString: String)
Return Value
An NSURL object initialized with URLString. If the URL string was malformed, returns nil.
Discussion
This method expects URLString to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding.
所以你必须检查 nil
在我为此填写雷达后,我得到了以下答案:
Apple Developer Relations
An empty string is a valid URL string. It has no scheme, no authority (user/password/host/port), an empty path, no query and no fragment.
所以它似乎按预期工作。