Xcode 在非可选字符串上返回 nil

ATC*_*ger 0 null xcode ios swift

我有一个接收图像和字符串的函数。当我尝试使用 () 功能将字符串放入更长的字符串时,它告诉我在解开可选项时发现 nil。例外它根本不是可选的,它是一个字符串。我可以打印出该值并正确显示。

func UpdateBusiness(logo: UIImage, category: String) {
        guard let bizID = UserDefaults.standard.string(forKey: defaultKeys.businessID) else {return}
        let thisURL = "http://mywebsite.com/api/v0.1/Business/EditBusinessLogoAndCategory?businessID=\(bizID)&category=\(category)"
        let combinedURL = URL(string: thisURL)!
}
Run Code Online (Sandbox Code Playgroud)

创建 URL 会使系统崩溃。我可以在调试器中看到 category 的值,并且我在这个字符串中没有可选项。它怎么能找到零?

小智 5

由于强制解包,此代码崩溃。在这种情况下可以推荐使用URLComponents。这比字符串连接更具可读性,并且对于大量参数字符串连接不是一个好的选择。

var components = URLComponents()
components.scheme = "http"
components.host = "mywebsite.com"
components.path = "/api/v0.1/Business/EditBusinessLogoAndCategory"
components.queryItems = [
    URLQueryItem(name: "businessID", value: bizID),
    URLQueryItem(name: "category", value: category)

]
let url = components.url



enter code here
Run Code Online (Sandbox Code Playgroud)