1

How do I turn an array, for example [Int] into a String keeping commas between elements? If I have an array like [1,2,3,4], I want to receive a String like "1, 2, 3, 4".

0

2 Answers 2

14

You can do:

let string = array.map { String($0) }
    .joined(separator: ", ")

The map call converts the array of numbers to an array of strings, and the joined combines them together into a single string with whatever separator you want between the individual strings.

Or, if this is to be presented in the UI the numbers could require either decimal points and/or thousands separators, then it's better to show the results in a localized format using NumberFormatter:

let array = [1.0, 1.1, 1.2, 1.3]
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

let string = array.compactMap { formatter.string(for: $0) }
    .joined(separator: ", ")

Which, for US users, would result in:

1.00, 1.10, 1.20, 1.30

But for German users, it would result in:

1,00, 1,10, 1,20, 1,30

And if you wanted this to be presented nicely as "A, B, and C", in iOS 13+ and/or macOS 10.15+ you can use ListFormatter:

let array = [1.0, 1.1, 1.2, 1.3]
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

let strings = array.compactMap { formatter.string(for: $0) }
if let result = ListFormatter().string(from: strings) {
    print(result)
}

Resulting in:

1.00, 1.10, 1.20, and 1.30

Sign up to request clarification or add additional context in comments.

Comments

2

You just need to map your integers into strings and join them with separator ", "

let array = [1,2,3,4]
let string = array.map(String.init).joined(separator: ", ")   //  "1, 2, 3, 4"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.