我知道如何通过编程来做到这一点,但我相信有一种内置的方式……

我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?


当前回答

如果你的问题是这样的: tobeFormattedString = ["a", "b", "c"] 输出= "abc"

String(tobeFormattedString)

其他回答

如果数组包含字符串,你可以使用String的join方法:

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

在Swift 2中:

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

如果您想使用特定的分隔符(连字符、空格、逗号等),这可能很有用。

否则,你可以简单地使用description属性,它返回数组的字符串表示形式:

let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"

提示:任何实现Printable协议的对象都有一个description属性。如果你在自己的类/结构中采用该协议,你也可以使它们打印友好

在Swift 3中

join变为joined,示例[nil, "1", "2"].flatMap({$0}).joined() joinWithSeparator变成了joined(separator:)(仅适用于字符串数组)

在Swift 4中

var array = ["1", "2", "3"]
array.joined(separator:"-")

Swift 2.0 Xcode 7.0 beta 6以上使用joinWithSeparator()代替join():

var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

joinWithSeparator被定义为SequenceType的扩展

extension SequenceType where Generator.Element == String {
    /// Interpose the `separator` between elements of `self`, then concatenate
    /// the result.  For example:
    ///
    ///     ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
    @warn_unused_result
    public func joinWithSeparator(separator: String) -> String
}

斯威夫特3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")

对于任何元素类型

extension Array {

    func joined(glue:()->Element)->[Element]{
        var result:[Element] = [];
        result.reserveCapacity(count * 2);
        let last = count - 1;
        for (ix,item) in enumerated() {
            result.append(item);
            guard ix < last else{ continue }
            result.append(glue());
        }
        return result;
    }
}

对于某些语言(如希伯来语或日语),分隔符可能不是一个好主意。 试试这个:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

对于其他数据类型,分别为:

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)