How do I convert a Swift Array to a String?
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
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
-
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)
In Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.
Turning an array of Character
s into a String
with no separator:
let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
Turning an array of String
s into a String
with no separator:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string) // prints: "BobDanBryan"
Turning an array of String
s into a String
with a separator between words:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string) // prints: "Bob Dan Bryan"
Turning an array of String
s into a String
with a separator between characters:
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"
Turning an array of Float
s into a String
with a separator between numbers:
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"
Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator()
instead of join()
:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
joinWithSeparator
is defined as an extension on 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
}
Swift 3
["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")