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

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


当前回答

现在,在iOS 13+和macOS 10.15+中,我们可能会使用ListFormatter:

let formatter = ListFormatter()

let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {
    print(string)
}

这将生成一个漂亮的自然语言字符串表示列表。美国用户将看到:

老谋子,拉里和卷毛

它将支持任何语言,其中(a)你的应用程序已本地化;并且(b)配置了用户的设备。例如,一个德国用户的应用程序支持德语本地化,他会看到:

莫、拉瑞、克利

其他回答

在Swift 4中

let array:[String] = ["Apple", "Pear ","Orange"]

array.joined(separator: " ")

如果你想转换自定义对象数组为字符串或逗号分隔字符串(csv),你可以使用

 var stringIds = (self.mylist.map{$0.id ?? 0}).map{String($0)}.joined(separator: ",")

归功于:莫迪 post:将int数组转换为逗号分隔的字符串

现在,在iOS 13+和macOS 10.15+中,我们可能会使用ListFormatter:

let formatter = ListFormatter()

let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {
    print(string)
}

这将生成一个漂亮的自然语言字符串表示列表。美国用户将看到:

老谋子,拉里和卷毛

它将支持任何语言,其中(a)你的应用程序已本地化;并且(b)配置了用户的设备。例如,一个德国用户的应用程序支持德语本地化,他会看到:

莫、拉瑞、克利

let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
    let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
   print("Result will be >>>  \(stringAfterCombining)")

结果将>>> Mani Singh iOS开发者

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
}