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]
?
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.
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.
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.
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]
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