代码之家  ›  专栏  ›  技术社区  ›  Tony Lin

Map方法如何处理字符串类型?

  •  2
  • Tony Lin  · 技术社区  · 7 年前

    我一直在浏览 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+“&”}?“?” ?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Sulthan    7 年前

    它不是 map 结束 String ,这是一个 地图 结束 String? ( Optional<String> )完全不同的方法。

    Optional.map

    当此可选实例不是nil时计算给定的闭包,并将unwrapped值作为参数传递。

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

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