Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Swift Array to a String?

Tags:

arrays

ios

swift

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?

like image 696
Troy Avatar asked Sep 13 '14 19:09

Troy


People also ask

How do I join an array of strings into a single string?

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.

How do you change an array in Swift?

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.

How do you reverse an array in Swift?

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.


1 Answers

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:"-") 
like image 137
Antonio Avatar answered Oct 13 '22 16:10

Antonio