我知道如何以编程方式执行此操作,但我确信有一种内置方法...
我使用的每种语言都有某种对象集合的默认文本表示形式,当您尝试将数组与字符串连接或将其传递给 print() 函数等时,它会吐出这些对象集合。 Apple 的 Swift 语言有一种内置方法可以轻松地将数组转换为字符串,或者我们在字符串化数组时总是必须明确吗?
最佳答案
如果数组包含字符串,则可以使用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
协议(protocol)的对象都有一个 description
属性。如果您在自己的类/结构中采用该协议(protocol),您也可以使它们打印友好
在Swift 3中
join
变为joined
,例如[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
变为joined(separator:)
(仅适用于字符串数组)
在Swift 4中
var array = ["1", "2", "3"]
array.joined(separator:"-")
关于ios - 如何将 Swift 数组转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51585142/