How do I convert a Swift Array to a String?

2019-01-01 10:20发布

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?

标签: ios arrays swift
18条回答
查无此人
2楼-- · 2019-01-01 10:26

To change an array of Optional/Non-Optional Strings

//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)

Here flatMap, compactMap skips the nil values in the array and appends the other values to give a joined string.

查看更多
余生无你
3楼-- · 2019-01-01 10:27

Since no one has mentioned reduce, here it is:

[0,1,1,0].map{"\($0)"}.reduce(""){$0+$1}//"0110"

In the spirit of functional programming

查看更多
笑指拈花
4楼-- · 2019-01-01 10:28

If you want to ditch empty strings in the array.

["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")

If you want to filter nil values as well:

["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")
查看更多
冷夜・残月
5楼-- · 2019-01-01 10:28

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"

String(tobeFormattedString)

查看更多
看淡一切
6楼-- · 2019-01-01 10:31

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"

In 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:

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

In Swift 3

  • join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

var array = ["1", "2", "3"]
array.joined(separator:"-")
查看更多
查无此人
7楼-- · 2019-01-01 10:33

In Swift 4

let array:[String] = ["Apple", "Pear ","Orange"]

array.joined(separator: " ")
查看更多
登录 后发表回答