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