0

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)

2 Answers 2

3

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.

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

1 Comment

Beautifully explained!
0

First of all change Any to AnyObject and try following:

matchedResults += (results as [AnyObject])

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.