我一直在浏览 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
在 String
, 这是一个 map
在 String?
(Optional<String>
)。一种完全不同的方法。
参见 Optional.map
Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.
基本上,代码可以重写为:
(urlComponents.percentEncodedQuery?.appending("&") ?? "") + query(parameters)
关于ios - map 方法如何作用于字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50663895/