How to get rid of array brackets while printing

后端 未结 2 1682
长情又很酷
长情又很酷 2021-01-19 16:19

While printing an array how to get rid of brackets from left and right?

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


        
2条回答
  •  不知归路
    2021-01-19 16:39

    You could 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 the joinWithSeparator method on SequenceType:

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

    Meaning 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: " ")
        }
    }
    

提交回复
热议问题