使用seperator","加入字符串数组,并添加",和"以加入Swift中的最后一个元素

Eri*_*ips 2 json swift

我正忙着在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: ", ")+".")
    }
}
Run Code Online (Sandbox Code Playgroud)

print行,我不知道我怎么会是最后一个前用逗号和空格加入阵列像我有,但增加"和".

谢谢!

fre*_*tag 14

由于 iOS 13.0+ / macOS 10.15+ Apple 提供了ListFormatter。另请参阅此处了解详细信息

数组可以简单地格式化为:

let elements = ["a", "b", "c"]
result = ListFormatter.localizedString(byJoining: elements)
Run Code Online (Sandbox Code Playgroud)

顾名思义,您还可以免费获得本地化。


Leo*_*bus 13

添加一个条件来检查你的String集合是否小于或等于2个元素,如果为true则只返回连接的两个元素," and "否则删除集合的最后一个元素,用分隔符连接元素", "然后重新添加最后一个元素最终分隔符", and ".

您可以将BidirectionalCollection协议约束的协议扩展到StringProtocol:

双向集合提供从任何有效索引向后遍历,不包括集合的startIndex.因此,双向集合可以提供额外的操作,例如提供对最后一个元素的有效访问的最后一个属性,以及以相反顺序呈现元素的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"
Run Code Online (Sandbox Code Playgroud)

斯威夫特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
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)