ios - 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 的值,而且我在这个字符串中没有任何选项。它怎么能找到零?
解决方案
由于强制展开,此代码正在崩溃。在这种情况下可以推荐使用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
推荐阅读
- python - 如何使用列表中的 strptime 获取秒时间
- javascript - XMLHttpRequest POST 响应不同于 API 测试响应(Postman、Apitester.com 等)
- oracle - 如何在 Oracle Apex 中使用表单修改数据库
- laravel - AWS Elastic Beanstalk 拒绝连接到数据库 - Laravel
- javascript - “'x' 不是函数或其返回值不可迭代”的意思错误
- graphql - 我想使用语言 java 在 graphql 查询参数中使用字符串数组
- caching - 如何将 esi 标签包含到主 esi 标签中?
- sql - 使用其他表的 Postgres 合并示例
- visual-studio-code - 如何关闭 vscode 的搜索开关?
- android - 将带有父类的可打包 Kotlin 类转换为 JSON