ios - map 方法如何在字符串类型上工作?
问题描述
我一直在浏览Alamofire
源代码,有一个代码片段我不明白它是如何工作的以及为什么工作。
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
这urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "")
是我不明白它是如何工作的以及为什么需要它。
然后我写了我的片段:
import Foundation
let a: String = "hello world"
a.map { $0 + "&" } //error: binary operator '+' cannot be applied to operands of type 'Character' and 'String'
print(a)
但它在map
方法上给出了错误。
为什么这不是工作,目的是urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "")
什么?
解决方案
这不是map
over String
,而是map
over String?
( Optional<String>
)。完全不同的方法。
当此 Optional 实例不为 nil 时,评估给定的闭包,将展开的值作为参数传递。
基本上,代码可以重写为:
(urlComponents.percentEncodedQuery?.appending("&") ?? "") + query(parameters)
推荐阅读
- r - 加速或替换for循环:组重塑和行绑定
- c++ - Opencv cascade.detectMultiScale 没有检测到眼睛
- reactjs - 将匹配传递给私人路线
- delphi - 如何释放不属于表单的对象
- entity-framework - DbSet.attach() 使下一个查询返回错误结果
- python - Using Pandas to create DataFrame out of complicated dictionary / list
- python-3.x - BERT:如何在 BioBERT 中使用 bert-as-service?
- .net - .NET MVC/WEB API 2 - 调试与发布中的异常处理
- python - 网络输入和输出
- javascript - 地点自动完成地址预测 html,当将其放入搜索框中时,它给了我一个!我不能打字