Concatenating an array to another optional values array with the “+=” operator

500 Views Asked by At

I have an array of object :

var fooArray = [Foo]()

If I want to append another array with Foo object i can use the += :

fooArray += anotherFooArray

This one works.

But if i'm making the Foo objects in the array optional :

var fooArray = [Foo?]()

Doing the concatenation raise an error :

[Foo?]() is not identical to 'CGFloat'

I definitely don't understand what's the problem and what CGFloat type has to do with this ?

3

There are 3 best solutions below

0
On BEST ANSWER

The problem is that Foo and Foo? are 2 different types (an optional is actually an instance of the Optional<T> enum).

In order to append into an array, the elements must be of the same type - Foo and Optional<Foo> aren't.

You can fix the problem by simply casting the array to append to an array of optional Foos:

fooArray += anotherFooArray as [Foo?]

As for the misleading error message, I think that it's trying to apply an overload of the += operator taking a CGFloat as one of the arguments, because it can't match the provided parameters with the overload defined for the array type.

0
On

If you want to get the array that only contains values and not nil s you can use reduce function to create new array.

let total: [Foo] = reduce(fooArray, otherArray) { acc, foo in
  if let foo = foo {
    return acc + [foo]
  } else {
    return acc
  }
}

Type of the fooArray is [Foo?] and type of otherArray is [Foo]

1
On

You are doing a couple of things wrong. An array in Swift is declared like this:

var array = []

Also if you want to make your objects in the array optional, the objects that you are passing should be optional as well:

class Goal {}

var goal1: Goal?
var goal2: Goal?
var goal3: Goal?
var goal4: Goal?

goal2 = Goal() // Initialized
goal4 = Goal() // Initialized

var array = [goal1?, goal2?, goal3?]

adding new object to the array is done by appending it:

array.append(goal4?)

This example array has [nil, Goal, nil, Goal] as goal 2 and 4 are initialised and the rest are nil. If you want to add an object to the array only if it exists use binding:

let goal1 = goal1 {
    array.append(goal1)
}

Hope this helps!