首页 > 解决方案 > 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 + "&" } ?? "")什么?

标签: iosswiftalamofire

解决方案


这不是mapover String,而是mapover String?( Optional<String>)。完全不同的方法。

Optional.map

当此 Optional 实例不为 nil 时,评估给定的闭包,将展开的值作为参数传递。

基本上,代码可以重写为:

(urlComponents.percentEncodedQuery?.appending("&") ?? "") + query(parameters)

推荐阅读