How to get rid of square brackets while printing

When printing an array, how do I get rid of the left and right brackets?

var array = ["1", "2", "3", "4"]
println("\(array)") //It prints [1, 2, 3, 4]

var arrayWithoutBracketsAndCommas = array. //some code

println("\(arrayWithoutBracketsAndCommas)") //prints 1 2 3 4

      

+3


source to share


1 answer


You can do:

extension Array {
    var minimalDescription: String {
        return " ".join(map { "\($0)" })
    }
}

["1", "2", "3", "4"].minimalDescription // "1 2 3 4"

      


With Swift 2, using Xcode b6, comes a method joinWithSeparator

on SequenceType

:

extension SequenceType where Generator.Element == String {
    ...
    public func joinWithSeparator(separator: String) -> String
}

      



The value you could do:

extension SequenceType {
    var minimalDescrption: String {
        return map { String($0) }.joinWithSeparator(" ")
    }
}

[1, 2, 3, 4].minimalDescrption // "1 2 3 4"

      

Swift 3:

extension Sequence {
    var minimalDescription: String {
        return map { "\($0)" }.joined(separator: " ")
    }
}

      

+10


source







All Articles