如何将 Swift 数组转换为字符串? [英] How do I convert a Swift Array to a String?
问题描述
我知道如何以编程方式执行此操作,但我确定有一种内置方法...
I know how to programmatically do it, but I'm sure there's a built-in way...
我使用过的每种语言都有某种默认文本表示,用于对象集合,当您尝试将 Array 与字符串连接或将其传递给 print() 函数等时,它会吐出这些表示.Apple 的 Swift 语言有一个内置的方法可以轻松地将数组转换为字符串,或者我们在对数组进行字符串化时总是必须明确?
Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift language have a built-in way of easily turning an Array into a String, or do we always have to be explicit when stringifying an array?
推荐答案
如果数组包含字符串,可以使用String
的join
方法:
If the array contains strings, you can use the String
's join
method:
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"
如果您想使用特定的分隔符(连字符、空格、逗号等),这会很有用.
This can be useful if you want to use a specific separator (hypen, blank, comma, etc).
否则你可以简单地使用 description
属性,它返回数组的字符串表示:
Otherwise you can simply use the description
property, which returns a string representation of the array:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
提示:任何实现Printable
协议的对象都有一个description
属性.如果您在自己的类/结构中采用该协议,您也可以使它们易于打印
Hint: any object implementing the Printable
protocol has a description
property. If you adopt that protocol in your own classes/structs, you make them print friendly as well
在 Swift 3
join
变成joined
,例如[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
变为joined(separator:)
(仅适用于字符串数组)
join
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)
在 Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
这篇关于如何将 Swift 数组转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!