Peter Schumacher
Peter Schumacher

Reputation: 441

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

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.

Upvotes: 1

Views: 1424

Answers (2)

Peter Schumacher
Peter Schumacher

Reputation: 441

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.

Upvotes: 5

vadian
vadian

Reputation: 285290

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

Upvotes: 0

Related Questions