RK-
RK-

Reputation: 12201

Is it possible to append a new object to a heterogenous array in swift?

I know that true mutability can not be achieved in swift. I have an array interspersed with different types of contents.

let myArray = String[]();
var array = ["First","Second","Third",1,0.4,myArray,"dsaa"]

I learned from the above post I have linked that we will be able to append items to an array. But each time I add a new item to the array I have declared above I get this error:

could not find an overload for '+=' that accepts the supplied arguments

But when the array is homogeneous, I am able to add an item which is same as the already present items, without hassle. but still the item with a different type can not be added.

Upvotes: 0

Views: 95

Answers (1)

Grimxn
Grimxn

Reputation: 22487

If you declare your second array explicitly as AnyObject[], you can do it:

let myArray = String[]()
var array:AnyObject[] = ["First", "Second", "Third", 1, 0.4, myArray, "dsaa"]
let n1 = array.count // 7
array += "next"
let n2 = array.count // 8

Upvotes: 2

Related Questions