任何人都可以建议清洁工是从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,我想按街道号,街道等的顺序排列。
答案 0 :(得分:3)
你现在可以在一个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"
}
}
}
答案 1 :(得分: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/
编辑 - 这只有在没有任何选项为零时才有效,如果一个是零,则情况不匹配。检查参考链接,了解如何检测可能为零的情况。