首页 > 解决方案 > Xcode 在非可选的字符串上返回 nil

问题描述

我有一个接受图像和字符串的函数。当我尝试使用 () 功能将字符串放入更长的字符串时,它告诉我它在展开可选时找到了 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)!
}

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

标签: iosswiftxcodenull

解决方案


由于强制展开,此代码正在崩溃。在这种情况下可以推荐使用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

推荐阅读