1

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

1 Comment

There's nothing wrong in my array declaration and you're example is kind of awful and don't answer my question. You should read Antonio's answer and some swift documentations.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.