我正忙着在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
行,我不知道我怎么会是最后一个前用逗号和空格加入阵列像我有,但增加"和".
谢谢!
添加一个条件来检查你的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 } }