meaning-matters meaning-matters - 3 months ago 10
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]?
{
didSet
{
self.wrappedObjects = objects.map{ 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
objects
makes
map
think
$0
is either a single
SomeClass
or an array
[SomeClass]
respectively?

Rob Rob
Answer

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.