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?
To change an array of Optional/Non-Optional Strings
Here flatMap, compactMap skips the nil values in the array and appends the other values to give a joined string.
Since no one has mentioned reduce, here it is:
In the spirit of functional programming
If you want to ditch empty strings in the array.
If you want to filter nil values as well:
If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"
String(tobeFormattedString)
If the array contains strings, you can use the
String
'sjoin
method:In Swift 2:
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:Hint: any object implementing the
Printable
protocol has adescription
property. If you adopt that protocol in your own classes/structs, you make them print friendly as wellIn Swift 3
join
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)In Swift 4
In Swift 4