LoginSignup
3
3

More than 5 years have passed since last update.

NSURLは空文字で初期化するとオブジェクトを返すが、Swift 3.0のURL型は空文字で初期化するとnilを返す。

Posted at

概要

Swift 3.0のURL型は初期化時に空文字が渡されるとnilになるっぽいです。

詳細

NSURLをSwiftで扱うと、空文字を初期化で渡したときに、NSURLのオブジェクトが作成されていました。

これを利用してユニットテスト内でNSURL(string: "")!とか書いて適当にオブジェクトを作っているところがあったのですが、Xcodd8のconvert機能を使ってNSURL -> URLの自動変換したときユニットテストがクラッシュするようになり気が付きました...

let nsurl = NSURL(string: "")
print(nsurl?.absoluteString) // => Optional("")

let url = URL(string: "")
print(url?.absoluteString) // => nil

参考資料

改めてドキュメント見ると、URLのところに空文字はnilと明記されています。

URL

Returns nil if a URL cannot be formed with the string 
(for example, if the string contains characters that are illegal in a URL, or is an empty string).

NSURL

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.

まとめ

やはりForce Unwrappingは使うもんじゃない...

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3