meaning-matters meaning-matters - 1 year ago 64
Swift Question

Misleading error: optionality of map's variable changes it from array to single object

I have:

private var wrappedObjects: [WrapperClass]?

var objects: [SomeClass]?
self.wrappedObjects ={ WrapperClass($0) }

This results in the following error:

`Cannot convert value of type '[SomeClass]' to expected argument type 'SomeClass'`

However when I just change one line to:

var objects: [SomeClass] = []

the error is gone.

Why does the optionality of
is either a single
or an array

Rob Rob
Answer Source

It's a misleading error. The problem is that you can't call map on an optional. You want employ some optional chaining, e.g.:

self.wrappedObjects = objects?.map { WrapperClass($0) }

That's assuming, of course, that there is an initializer for WrapperClass that can take a SomeClass (without any external parameter name) and return a WrapperClass.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download