当前位置:  开发笔记 > 前端 > 正文

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

如何解决《使用seperator","加入字符串数组,并添加",和"以加入Swift中的最后一个元素》经验,为你挑选了1个好方法。

我正忙着在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行,我不知道我怎么会是最后一个前用逗号和空格加入阵列像我有,但增加"和".

谢谢!



1> Leo Dabus..:

添加一个条件来检查你的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"

斯威夫特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
    }
}

推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有