Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join string array with separator ", " and add ", and " to join the last element in Swift

Tags:

json

swift

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: ", ")+".")
    }
}

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.

Thank you!

like image 559
Eric Phillips Avatar asked Jan 24 '17 02:01

Eric Phillips


People also ask

How to join array elements in Swift?

In Swift, we are allowed to join the elements of an array in a string using joined() function. This function creates a new string by concatenating all the elements of an array using a specified separator. We can also join all the elements of an array without any separator.

How do I merge two arrays in Swift?

var Array1 = ["Item 1", "Item 2"] var Array2 = ["Thing 1", "Thing 2"] var Array3 = Array1 + Array2 // Array 3 will just be them combined :) Save this answer.

How do you join an element in an array?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.


2 Answers

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 ".

You can extend BidirectionalCollection protocol constraining its elements to the StringProtocol:

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 or later

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"
like image 93
Leo Dabus Avatar answered Sep 28 '22 04:09

Leo Dabus


Since iOS 13.0+ / macOS 10.15+ Apple provides the ListFormatter. See also here for details.

Arrays can be formatted as easy as:

let elements = ["a", "b", "c"]
result = ListFormatter.localizedString(byJoining: elements)

As the function name suggests, you also get the localization for free.

like image 25
freytag Avatar answered Sep 28 '22 05:09

freytag