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!
}
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 benil
, which can definitely happen (as you have discovered). Therefore, simply change yourpublic var url: URL
to returnURL?
instead. Then just returncomponents.url
. This puts the onus on the caller to check whetherurl
isnil
, and it can proceed to unwrap safely by using the usualif let url
dance.