11

I'm trying to create an URL variable from a string value. I don't understand why the resulting URL is nil

I have set up a new Xcode macOS project, placed a simple button on the View, created an action for that button and implemented the following code. The resulting url is nil.

I tried the same in Swift playground and there it worked...

    @IBAction func buttonClicked(_ sender: Any) {
        let urlAsString = "http://www.google.de/"
        let url = URL(string: urlAsString)

        if url != nil {
            // Do work...
        }
    }

urlAsString is "http://www.google.de/" but url is nil

debugger

John
  • 117
  • 1
  • 8
  • @Sh_Khan does not for me. Check my edited post. I have attached a screenshot from the debugger – John Sep 29 '19 at 12:13
  • Change “do work” comment to print statement `print("it worked")`. Run the app, no breakpoint. Does it print? – matt Sep 29 '19 at 13:59
  • @matt Yes, it does print "it worked". Seems to only display the wrong variable content? – John Sep 29 '19 at 14:39
  • Okay that's great! So either (1) you're using the debugger wrong, or (2) the debugger has a bug - it displays `nil` but the thing is _not_ nil. And (2) is perfectly possible! So either way, you have nothing to worry about; your code is working fine. The problem is just the debugger display of the value of `url`. Don't worry, be happy. – matt Sep 29 '19 at 15:01

1 Answers1

26

You've found a bug in the debugger!

[This bug is slated to be fixed in Xcode 12.5.]

It's easy to reproduce it:

enter image description here

We have paused at a breakpoint inside the condition. So obviously url is not nil or we wouldn't be here at all.

Another way to prove this is to po url in the console (see right-bottom of this screen shot):

enter image description here

Nevertheless, url shows as nil both in the tooltip and in the variables list. So the debugger is just lying to you: url is not nil. Don't worry, be happy. Your code is working fine.

EDIT The bug has something to do with the Swift Foundation overlay. If you change the declaration of url to this:

let url = NSURL(string: urlAsString)

...then everything works as expected.

And see also https://stackoverflow.com/a/58156592/341994

matt
  • 447,615
  • 74
  • 748
  • 977
  • Thanks for the detailed explanation. As an Swift novice I would have never thought about finding a bug in Xcode :-) – John Sep 29 '19 at 18:04
  • "Don't worry?". This bug has high potential for causing lots of errors and hours of wasted time :/. Thanks @matt for showing how to easily reproduce it, so I can file another bug report. – heyfrank Dec 10 '19 at 17:23
  • I've just started to learn Swift and was confused A LOT, spent 2 hours before finding this answer :( – Smit Apr 19 '20 at 14:15
  • Man!!!!! I have stared at screen for 4 hrs, poking some code that actually works, switching between URL NSURL, all because of this debugger bug, Thanks @matt for this post :) – infinity_coding7 May 08 '20 at 23:24