Search code examples
swiftnsurl

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.


Solution

  • 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.