用分隔符“,"将字符串数组连接起来并添加“和"加入Swift的最后一个元素 [英] Join string array with separator ", " and add ", and " to join the last element in Swift
问题描述
我在一个快速的操场上用SwiftyJSON解析JSON.我的代码如下:
I'm messing around with parsing JSON with SwiftyJSON on a swift playground. My code is as follows:
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
行上,我想知道如何像我一样用逗号和空格连接数组,但是在最后一个之前添加"and".
On the print
line, I was wondering how I could join the arrays with a comma and space like I have, but add "and" before the last one.
谢谢!
推荐答案
添加条件以检查您的String
集合是否少于或等于2个元素,如果为true,则仅返回由" and "
联接的两个元素否则,请删除集合的最后一个元素,将这些元素与分隔符", "
结合在一起,然后用最后一个分隔符", and "
重新添加最后一个元素.
Add a condition to check if your String
collection has less than or is equal to 2 elements, if true just return the two elements joined by " and "
otherwise drop the last element of your collection, join the elements with a separator ", "
then re add the last element with the final separator ", and "
.
您可以扩展BidirectionalCollection
协议,将其元素限制为StringProtocol
:
You can extend BidirectionalCollection
protocol constraining its elements to the StringProtocol
:
双向集合提供了从任何有效路径向后遍历的功能 索引,不包括集合的startIndex.双向的 因此,集合可以提供其他操作,例如 last 属性,可以有效访问最后一个元素和 reversed()方法以相反的顺序显示元素.
Bidirectional collections offer traversal backward from any valid index, not including a collection’s startIndex. Bidirectional collections can therefore offer additional operations, such as a last property that provides efficient access to the last element and a reversed() method that presents the elements in reverse order.
Xcode 11.4•Swift 5.2或更高版本
extension BidirectionalCollection where Element: StringProtocol {
var sentence: String {
count <= 2 ?
joined(separator: " and ") :
dropLast().joined(separator: ", ") + ", and " + last!
}
}
let elements = ["a", "b", "c"]
let sentenceFromElements = elements.sentence // "a, b, and c"
这篇关于用分隔符“,"将字符串数组连接起来并添加“和"加入Swift的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!