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

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


当前回答

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

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

其他回答

Swift等价于你所描述的是字符串插值。如果你考虑JavaScript做“x”+数组,在Swift中等价的是“x\(数组)”。

一般来说,字符串插值和Printable协议之间有一个重要的区别。只有特定的类符合Printable。每个类都可以以某种方式插入字符串。这在编写泛型函数时很有帮助。您不必将自己限制在Printable类上。

我的工作在NSMutableArray与componentsJoinedByString

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

如果你有字符串数组列表,那么转换为Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

它会给你字符串值

你可以使用循环来完成这个任务。或者使用地图。

通过映射:

let array = ["one" , "two" , "three"]
    
array.map({$0}).joined(seperator : ",")

在分隔符中,你可以修改字符串。

Output-> ("one,two,three")

当您想要将结构类型的列表转换为字符串时,请使用此方法

struct MyStruct {
  var name : String
  var content : String
}

let myStructList = [MyStruct(name: "name1" , content: "content1") , MyStruct(name: "name2" , content: "content2")]

然后像这样隐藏你的数组

let myString = myStructList.map({$0.name}).joined(separator: ",")

将产生===> "name1,name2"