Define protocol with property of Any type?

Is is possible to define a protocol with a type that can hold Any type of value?

i.e.

protocol MyProtocol {
    var foo: Any? {get set}
}

struct A : MyProtocol {
    var foo : String?
}

struct C : MyProtocol {
    var foo : Int?
}

Basically, I just need implimenting structs to have the property, regardless of type.

If I do this, I can create the protocol, but get an error from the structs that they are do not conform to the protocol.

You should either specify an associated type that the structs will use (preferably)

protocol MyProtocol {
  associatedtype Foo
  var foo: Foo? {get set}
}

struct A : MyProtocol {
  var foo : String?
}

struct C : MyProtocol {
  var foo : Int?
}

or use Any instead of concrete types in the structs as well:

protocol MyProtocol {
  var foo: Any? {get set}
}

struct A : MyProtocol {
  var foo : Any?
}

struct C : MyProtocol {
  var foo : Any?
}
1 Like

Thank you! It looks like associatedTypes are exactly what I was looking for. Reading up on them now.

1 Like