Join lists naturally, in any language

Turn an array of word into a sentence with the right commas and the right word for "and" or "or", without string joining.

iOS 15+macOS 12+ Swift 5.9

Joining names with commas and sticking “and” before the last one is fiddly, and the rules differ: American English adds a comma before “and”, British English does not depending on your stance on Oxford Commas, and other languages use their own words for “and” anyway. The list format style handles all of it.

SharedWithView.swift
import SwiftUI

struct SharedWithView: View {
    let names = ["Ana", "Ben", "Chloé"]
    let sizes = [3, 5, 8]

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Shared with \(names, format: .list(type: .and))")
            Text("Ask \(names, format: .list(type: .or))")
            Text("Sizes \(sizes, format: .list(memberStyle: .number, type: .and))")
        }
    }
}

#Preview("United Kingdom") {
    SharedWithView()
        .environment(\.locale, Locale(identifier: "en_GB"))
}

#Preview("France") {
    SharedWithView()
        .environment(\.locale, Locale(identifier: "fr_FR"))
}

How it works

Gotchas

See also