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.
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
.list(type: .and)and.list(type: .or)join strings with the separators and conjunction of the locale.- Two items get no comma (“Ana and Ben”); one item is shown on its own; an empty array gives an empty string.
memberStyle:formats each element first, so numbers, percentages and dates join just as well:.list(memberStyle: .percent, type: .or)gives “10% or 25%”.width: .shortuses the shortest form the language has, such as “Ana, Ben, & Chloé” in American English.
Gotchas
- Inside
Text, use the interpolation withformat:so the environment’s locale applies. A.formatted()call in the view uses the device’s locale instead. - The words around the list are not translated by the format style. Put the whole sentence in your string catalog, with the list as an argument.
- Very long lists are still joined in full. Show the first few names and a count (“Ana, Ben and 12 others”) when space is short.