Search code examples
iosswiftcocoa-touchfoundation

Swift: Turn array into String


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


Solution

  • 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