NSURL fail able initialiser initWithString: does not return nil on empty String in Swift

。_饼干妹妹 提交于 2019-12-20 04:53:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!