Convert String to Url (Why Is Resulting Variable Nil)

Convert String to URL (Why is resulting variable nil)

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:

Sample Image

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):

Sample Image

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

Swift. URL returning nil

Don't force unwrap it with (!). When you use (!) and the value of the variable is nil, your program crashes and you get that error. Instead, you want to safely unwrap the optional with either a "guard let" or an "if let" statement.

guard let name = element.Name as? String else {
print("something went wrong, element.Name can not be cast to String")
return
}

if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
UIApplication.shared.openURL(url)
} else {
print("could not open url, it was nil")
}

If that doesn't do the trick, you may have an issue with element.Name. So I would check to see if that's an optional next if you're still having issues.

Update

I added a possible way to check the element.Name property to see if you can cast it as a String and create the desired url you're looking to create. You can see the code above the code I previously posted.

NSURL return nil?

Assuming you're not using ARC, the problem is that you're assigning objects you don't own to instance variables. If the objects have no owners, they can be deallocated at any time. You should claim ownership of the objects, preferably by using accessors instead of directly setting the variables themselves.

How to convert String URL in Swift 5?

Honestly, looks like you managed to get some trash into the string by copy-pasting, I'm assuming it's encoding or something. This code from below works just fine:

let test = "https://api-staging.xx.oo/v1/s-locations/"
let url = URL(string: test)


Related Topics



Leave a reply



Submit