安全展开URL类型



我形成了一个url来传递在请求旁边,作为回报,我的应用程序崩溃了,因为它在调试时意外地发现了nil ->我有url,我的问题是,如何避免使用强制展开?当我使用guard或if let时,我应该返回什么?网址吗?它将再次是可选的。使var url: URL?对我也不好。

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

绝对不要使用感叹号。它的意思是"crash me"。当崩溃时,您几乎不会感到惊讶,因为这正是您说要做的。

如果components.url变成nil,您没有返回有用的值,这肯定会发生(如您所发现的)。因此,只需将public var url: URL更改为返回URL?即可。然后返回components.url。这就把检查url是否为nil的责任推给了调用者,它可以通过使用通常的if let url舞蹈安全地展开。

最新更新