我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
当前回答
如果你有字符串数组列表,那么转换为Int
let arrayList = list.map { Int($0)!}
arrayList.description
它会给你字符串值
其他回答
修改一个可选/非可选字符串数组
//Array of optional Strings
let array : [String?] = ["1",nil,"2","3","4"]
//Separator String
let separator = ","
//flatMap skips the nil values and then joined combines the non nil elements with the separator
let joinedString = array.flatMap{ $0 }.joined(separator: separator)
//Use Compact map in case of **Swift 4**
let joinedString = array.compactMap{ $0 }.joined(separator: separator
print(joinedString)
这里是flatMap, compactMap跳过数组中的nil值,并附加其他值以给出一个连接字符串。
在Swift 2.2中,你可能不得不将数组转换为NSArray来使用componentsJoinedByString(",")
let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")
你可以使用循环来完成这个任务。或者使用地图。
通过映射:
let array = ["one" , "two" , "three"]
array.map({$0}).joined(seperator : ",")
在分隔符中,你可以修改字符串。
Output-> ("one,two,three")
如果你的问题是这样的: tobeFormattedString = ["a", "b", "c"] 输出= "abc"
String(tobeFormattedString)
现在,在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)配置了用户的设备。例如,一个德国用户的应用程序支持德语本地化,他会看到:
莫、拉瑞、克利