-3

Im forming a url to pass in next to request, in return my app crashes, because it unexpectedly finds nil, when debuggin -> i do have url, so my question, how can i avoid using force unwrap here ? when i use guard or if let, what should i return instead ? URL ? it will be optional again. Making var url: URL? not good for me also.

public var url: URL {
    var components = URLComponents()
    components.scheme = scheme
    components.host = ipAddress
    components.path = endpoint
    components.port = port
    components.queryItems = urlQueryItems
    return components.url!.removingPercentEncoding!
}
Sprite
  • 39
  • 4
  • Without context, no one will be able to tell you what default value should you use for an invalid `URL`. What does this URL represent? Are the inputs dynamic? Is there a meaningful default URL you can use? If not, you need to stop the context where you'd be using the `URL` that couldn't be created. – Dávid Pásztor Nov 30 '22 at 14:26
  • 1
    `removingPercentEncoding` seems to be counterproductive because `URLComponents` adds percent encoding dynamically where necessary. – vadian Nov 30 '22 at 14:29

1 Answers1

1

Never use an exclamation mark. It means "crash me". You can hardly be surprised when you do crash, because that is precisely what you said to do.

You have no useful value to return if components.url turns out to be nil, which can definitely happen (as you have discovered). Therefore, simply change your public var url: URL to return URL? instead. Then just return components.url. This puts the onus on the caller to check whether url is nil, and it can proceed to unwrap safely by using the usual if let url dance.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Note that the `if let` dance is greatly smoothed in Xcode 14; you no longer need to say `if let url = url`. – matt Nov 30 '22 at 14:52