我如何转换斯威夫特阵列为字符串? [英] 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...
我用每一种语言都有某种默认的文本再presentation为对象的集合,它会吐出你试图用一个字符串来连接的阵列,或将其传递给print()函数等有没有苹果的雨燕语言都容易转向数组为一个字符串,还是我们始终有一个内置的方式来字符串化数组时要明确?
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?
推荐答案
如果数组包含字符串,你可以使用字符串
的加入
方法:
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"
在 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).
否则,你可以简单地使用说明
属性,它返回一个字符串重数组的presentation:
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]"
提示:实施打印
协议的任何对象有一个说明
属性。如果你采用在自己的类/结构的协议,你让他们打印友好以及
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
这篇关于我如何转换斯威夫特阵列为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!