本文翻译自: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... 我知道如何以编程方式进行操作,但是我敢肯定有一种内置方法...
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? 我使用的每种语言都有一组对象的默认文本表示形式,当您尝试将Array与字符串连接起来或将其传递给print()函数时,它将吐出。Apple的Swift语言是否可以有一种轻松地将数组转换为字符串的内置方法,还是在对数组进行字符串化时始终必须明确?
参考:https://stackoom.com/question/1kMn3/如何将Swift数组转换为字符串
If the array contains strings, you can use the String
's join
method: 如果数组包含字符串,则可以使用String
的join
方法:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2 : 在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). 如果要使用特定的分隔符(连字符,空格,逗号等),这可能很有用。
Otherwise you can simply use the description
property, which returns a string representation of the array: 否则,您可以简单地使用description
属性,该属性返回数组的字符串表示形式:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. 提示:任何实现Printable
协议的对象都具有description
属性。 If you adopt that protocol in your own classes/structs, you make them print friendly as well 如果您在自己的类/结构中采用该协议,则也使它们易于打印
In Swift 3 在Swift 3中
join
becomes joined
, example [nil, "1", "2"].flatMap({$0}).joined()
join
变得joined
,例如[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomes joined(separator:)
(only available to Array of Strings) joinWithSeparator
变为joinWithSeparator
joined(separator:)
(仅适用于字符串数组) In Swift 4 在Swift 4中
var array = ["1", "2", "3"]
array.joined(separator:"-")
The Swift equivalent to what you're describing is string interpolation. 与您描述的Swift等效的是字符串插值。 If you're thinking about things like JavaScript doing "x" + array
, the equivalent in Swift is "x\\(array)"
. 如果您考虑使用JavaScript做"x" + array
类的事情,那么Swift中的等效项就是"x\\(array)"
。
As a general note, there is an important difference between string interpolation vs the Printable
protocol. 作为一般说明,字符串插值与Printable
协议之间存在重要区别。 Only certain classes conform to Printable
. 仅某些类符合Printable
。 Every class can be string interpolated somehow. 每个类都可以以某种方式插入字符串。 That's helpful when writing generic functions. 这在编写泛型函数时很有用。 You don't have to limit yourself to Printable
classes. 您不必仅限于Printable
类。
Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator()
instead of join()
: Swift 2.0 Xcode 7.0 beta 6及更高版本使用joinWithSeparator()
而不是join()
:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
joinWithSeparator
is defined as an extension on SequenceType
joinWithSeparator
被定义为SequenceType
的扩展
extension SequenceType where Generator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
@warn_unused_result
public func joinWithSeparator(separator: String) -> String
}
Mine works on NSMutableArray with componentsJoinedByString 我的工作与组件JoinedByString NSMutableArray
var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"
With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem. 使用Swift 5,您可以根据需要选择以下Playground示例代码之一来解决您的问题。
Character
s into a String
with no separator: 将Character
数组转换为不带分隔符的String
: let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
String
s into a String
with no separator: 将String
数组转换为不带分隔符的String
: let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string) // prints: "BobDanBryan"
String
s into a String
with a separator between words: 将String
数组转换为单词之间带有分隔符的String
: let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string) // prints: "Bob Dan Bryan"
String
s into a String
with a separator between characters: 将String
数组转换为在字符之间使用分隔符的String
: let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")
print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"
Float
s into a String
with a separator between numbers: 将Float
数组转换为String
,并在数字之间使用分隔符: let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")
print(string)
// prints "12.0-14.6-35.0"