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?
join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.
To reverse a Swift Array, call reverse() or reversed() method on the array. reverse() method reverses the elements of the array in place. reversed() method creates a new array with the elements of the original array reversed, and returns this new 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"
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:"-")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With