问题
It is easy to reproduce in a Playground
import Foundation
let urlString = ""
let url = NSURL(string: urlString)
print(url)
The result of url is somehow (no URL)
instead of the expected nil
and the printout is Optional()
with neither .Some
or .None
.
I would really like some insight on this one, because it caught me by surprise and causes a crash in production code.
回答1:
After i filled a Radar for this i got the following answer:
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.
So it seems to be working as expected.
回答2:
The best way to find out is to read the documentation
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.
So you have to check for nil
来源:https://stackoverflow.com/questions/32784552/nsurl-fail-able-initialiser-initwithstring-does-not-return-nil-on-empty-string