safe unwrap URL type

299 Views Asked by At

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!
}
1

There are 1 best solutions below

1
On

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.