0

while this link: Add an element to an array in Swift shows how to add an item to an array, my question is about adding an array as an item to another array.

I did not find any similar question - I have these arrays:

[1,2,3] and [4,5,6]

I want to append the first array to the other one as a whole, so I get this result:

[4,5,6,[1,2,3]]

Please note that this is NOT expected result:

[4,5,6,1,2,3]

How would I achieve this?

Community
  • 1
  • 1
Sharonica
  • 183
  • 1
  • 5
  • 14

3 Answers3

2

At this case, the container array should be of type [Any] to let it contains ints and array of ints.

let arr1 = [1,2,3] // by default, it should be of type [Int]
let arr2:[Any] = [4,5,6,arr1]

print(arr2) // [4, 5, 6, [1, 2, 3]]

Note that Swift is strongly typed, by default, array must be an array of ints, -unlike Objective-C- array cannot contains mix of data types.

That's why you should Any type:

Any can represent an instance of any type at all, including function types.

Note that:

Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.


Accessing Elements:

By default, accessing elements from [Any] array should be of type of Any, for example:

let numberOne = arr2[0] // type of Any
let myArray = arr2[3] // type of Any

For getting the desired data type, you should cast it using as? operator with optional binding, as follows:

if let oneInt = arr2[0] as? Int {
    print("one is an Int and it equals to: \(oneInt)")
} else {
    print("one is NOT ad Int")
}
// one is an Int and it equals to: 4

if let oneString = arr2[0] as? String {
    print("one is an Int and it equals to: \(oneString)")
} else {
    print("one is NOT ad Int")
}
// one is NOT ad Int

Remark: using as! operator will cause the application to crash if the type does not matched.

let oneInt = arr2[0] as! Int // works fine
let oneString = arr2[0] as! String // CRASH!

For more information about as operators you might want to check this Q&A and the Type Casting Documentation.

Community
  • 1
  • 1
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
1
var a: [Any] = [1,2,3]
var b: [Int] = [3,4,5]
a.append(b) // [1, 2, 3, [3, 4, 5]]
Shubham
  • 935
  • 1
  • 7
  • 25
1
var arrayOne = [1,2,3]
var arrayTwo = [4,5,6]

if you want result as : [4,5,6,[1,2,3]]

arrayTwo.append(arrayOne)

above code will convert arrayOne as a single element and add it to the end of arrayTwo.

if you want result as : [4,5,6,1,2,3] then,

arrayTwo.append(contentsOf: arrayOne)

above code will add all the elements of arrayOne at the end of arrayTwo.

Thanks.

meMadhav
  • 233
  • 2
  • 12