3

任何人都可以建议清洁工从 CLPlacemark 创建一个地址字符串。

目前我正在使用这个扩展

extension CLPlacemark {

    func makeAddressString() -> String {
        var address = ""
        if subThoroughfare != nil { address = address + " " + subThoroughfare! }
        if thoroughfare != nil { address = address + " " + thoroughfare! }
        if locality != nil { address = address + " " + locality! }
        if administrativeArea != nil { address = address + " " + administrativeArea! }
        if postalCode != nil { address = address + " " + postalCode! }
        if country != nil { address = address + " " + country! }
        return address
    }
}

所有实例变量都是可选的,因此检查 nil,我希望以相同的街道号顺序,到街道等。

4

3 回答 3

7

CLPlacemark有一个postalAddress类型的属性CNPostalAddress可以使用CNPostalAddressFormatter.

let formatter = CNPostalAddressFormatter()
let addressString = formatter.string(from: placemark.postalAddress)
于 2019-03-10T22:33:22.740 回答
5

您现在可以在 Optionals 数组上进行 flatMap 以过滤掉 nil 值(我认为这从 Swift 2 开始有效)。您的示例现在基本上是单行的(如果您删除了我为便于阅读而插入的换行符):

extension CLPlacemark {

    func makeAddressString() -> String {
        return [subThoroughfare, thoroughfare, locality, administrativeArea, postalCode, country]
            .flatMap({ $0 })
            .joined(separator: " ")
    }
}

您可以更进一步,并使用嵌套数组来实现更复杂的样式。以下是德国风格缩短地址 ( MyStreet 1, 1030 City) 的示例:

extension CLPlacemark {

    var customAddress: String {
        get {
            return [[thoroughfare, subThoroughfare], [postalCode, locality]]
                .map { (subComponents) -> String in
                    // Combine subcomponents with spaces (e.g. 1030 + City),
                    subComponents.flatMap({ $0 }).joined(separator: " ")
                }
                .filter({ return !$0.isEmpty }) // e.g. no street available
                .joined(separator: ", ") // e.g. "MyStreet 1" + ", " + "1030 City"
        }
    }
}
于 2017-08-17T12:20:51.700 回答
0

这也应该有效。

extension CLPlacemark {

  func makeAddressString() -> String {
    // Unwrapping the optionals using switch statement
    switch (self.subThoroughfare, self.thoroughfare, self.locality, self.administrativeArea, self.postalCode, self.country) {
    case let (.Some(subThoroughfare), .Some(thoroughfare), .Some(locality), .Some(administrativeArea), .Some(postalCode), .Some(country)):
        return "\(subThoroughfare), \(thoroughfare), \(locality), \(administrativeArea), \(postalCode), \(country)"
    default:
        return ""
    }
  }
}

查看这篇文章以供参考: http: //natashatherobot.com/swift-unwrap-multiple-optionals/

编辑 - 这仅在没有任何选项为 nil 时才有效,如果一个为 nil,则大小写将不匹配。查看参考链接,了解如何检测一个可能为零的情况。

于 2015-10-29T18:13:08.857 回答