3

I am trying to create an array of struct instances like this:

let installers: [AnyObject] = [Homebrew(), Ls()]

But I get this error:

value of type 'Homebrew' does not conform to expected element type 'AnyObject'

When I give the array no type, I get an ambiguous type error and that it needs more context.

Is it possible to accomplish what I am trying to do?

I Googled all over, but I can't find anything.

2
  • 10
    Note that while Adam is correct in the syntax, this is almost always the wrong design. There should be some protocol that both Homebrew and Ls conform to, and you should make your array of that protocol rather than Any. Any breaks Swift's type safety and creates many tricky corner cases and subtle bugs (particularly if generics or Optionals are ever involved). It should be avoided except where absolutely necessary. (The same is equally true of AnyObject.) Commented Mar 28, 2016 at 17:45
  • @RobNapier Agreed. Commented Mar 28, 2016 at 18:49

3 Answers 3

5

For structs use Any instead of AnyObject.

let installers: [Any] = [Homebrew(), Ls()]
Sign up to request clarification or add additional context in comments.

Comments

2

As Rob proposed above, I have created a simple protocol type InstallerType to help you with this. Instead of having it to conform to Any or AnyObject protocols, conforming it to some specific type would categorise your objects in better way.

extension Homebrew: InstallerType { }
extension Ls: InstallerType { }

let installers: [InstallerType] = [Homebrew(), Ls()]

Comments

2

Following @RobNapier 's suggestion from his comment, I built a protocol. Because both structs use the id and command constants, I came up with this:

protocol CKInstall {
  var id: String {get}
  var command: [String] {get}
}

Problem solved!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.