Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate or merge arrays in Swift?

If there are two arrays created in swift like this:

var a:[CGFloat] = [1, 2, 3] var b:[CGFloat] = [4, 5, 6] 

How can they be merged to [1, 2, 3, 4, 5, 6]?

like image 546
Hristo Avatar asked Aug 05 '14 19:08

Hristo


People also ask

How do you concatenate an array?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do I append one array to another in Swift?

To append another Array to this Array in Swift, call append(contentsOf:) method on this array, and pass the other array for contentsOf parameter. append(contentsOf:) method appends the given array to the end of this array.

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.


1 Answers

You can concatenate the arrays with +, building a new array

let c = a + b print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] 

or append one array to the other with += (or append):

a += b  // Or: a.append(contentsOf: b)  // Swift 3 a.appendContentsOf(b)    // Swift 2 a.extend(b)              // Swift 1.2  print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] 
like image 61
Martin R Avatar answered Oct 04 '22 15:10

Martin R