Bernd
Bernd

Reputation: 11523

Adding objects of a specific type to a generic Array<Any> in Swift?

How do you add an object of a specific type to a generic Array:[Any]? My understanding is that Any should be able to contain any other object. Is this correct? Unfortunately I get an error message when I add specific objects to the generic array.

Example

An array of objects of type "SpecificItemType"

var results:[SpecificItemType] = []
... // adding various objects to this array

The generic target array for these objects

var matchedResults:[Any] = []
matchedResults += results

Error Message

[Any] is not identical to UInt8

What's the problem here? The error message didn't really help.

One more note: Interestingly it is possible to add single objects using append. so the following works

matchedResults.append(results.first)

Upvotes: 0

Views: 168

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

The compiler cannot resolve the type constraints on

func +=<T, C : CollectionType where T == T>(inout lhs: ContiguousArray<T>, rhs: C)

because you're trying to add [SpecificType] to [Any], hence T != T.

You can fix this by upcasting the most specific array.

var r = results.map { $0 as Any }
matchedResults += r

Concerning the puzzling error, it's due to the overloading on the += operator. The compiler tries to resolve the various versions of the operator, eventually finding this one here:

func +=(inout lhs: UInt8, rhs: UInt8)

Probably it's the last one it tries to resolve, so it throws an error here, telling you that [Any] is different than the expected type for lhs, i.e. UInt8 in this case.

Upvotes: 3

tgebarowski
tgebarowski

Reputation: 1379

First of all change Any to AnyObject and try following:

matchedResults += (results as [AnyObject])

Upvotes: 0

Related Questions