我正忙着在Swiftty操场上使用SwiftyJSON解析JSON。我的代码如下:
import UIKit
import SwiftyJSON
var partyList: [String] = []
var firstPresidentList: [String] = []
if let url = URL(string:"http://mysafeinfo.com/api/data?list=presidents&format=json") {
if let data = try? Data(contentsOf: url) {
let json = JSON(data: data)
for i in 1...43 {
let party = json[i]["pp"].stringValue
let president = json[i]["nm"].stringValue
if partyList.contains(party) {
print("\n")
} else {
partyList.append(party)
firstPresidentList.append(president)
}
}
print("All the different parties of U.S. presidents included "+partyList.joined(separator: ", ")+", in that order. The first presidents of those parties were (repectively) "+firstPresidentList.joined(separator: ", ")+".")
}
}
在print
行上,我想知道如何使用逗号和空格加入数组,就像我一样,但添加"和#34;在最后一个之前。
谢谢!
答案 0 :(得分:11)
添加条件以检查您的String
集合是否小于或等于2个元素,如果为true则返回" and "
加入的两个元素,否则删除集合的最后一个元素,加入具有分隔符", "
的元素然后使用最终分隔符", and "
重新添加最后一个元素。
您可以将BidirectionalCollection
协议的约束扩展到StringProtocol
:
双向集合从任何有效集合向后提供遍历 index,不包括集合的startIndex。双向 因此,集合可以提供其他操作,例如 last 属性,可以有效访问最后一个元素和a reverse()方法以相反的顺序显示元素。
Swift 4.2或更高版本
extension BidirectionalCollection where Element: StringProtocol {
var sentence: String {
guard let last = last else { return "" }
return count <= 2 ? joined(separator: " and ") :
dropLast().joined(separator: ", ") + ", and " + last
}
}
let elements = ["a", "b", "c"]
let sentenceFromElements = elements.sentence // "a, b, and c"
Swift 4
extension BidirectionalCollection where Iterator.Element == String, SubSequence.Iterator.Element == String {
var sentence: String {
guard let last = last else { return "" }
return count <= 2 ? joined(separator: " and ") :
dropLast().joined(separator: ", ") + ", and " + last
}
}
Swift 3.1或更高版本
extension Array where Element == String {
var sentence: String {
guard let last = last else { return "" }
return count <= 2 ? joined(separator: " and ") :
dropLast().joined(separator: ", ") + ", and " + last
}
}
答案 1 :(得分:2)
从iOS 13.0+ / macOS 10.15+开始,Apple提供了ListFormatter。另请参见here for details。
数组的格式可以很简单:
let elements = ["a", "b", "c"]
result = ListFormatter.localizedString(byJoining: elements)
正如函数名称所建议的那样,您还可以免费获得本地化。