Protocol conformance failure

The error says ItemProtocol does not conform to ItemProtocol.
That doesn't make sense. It seems this should work fine.

// It's all clean until the last line
protocol ItemProtocol : class {
var message: String { get }
}

// heterogenious types
class A : ItemProtocol {
var message = "A"
}

class B : ItemProtocol {
var message = "B"
}

var items: [ItemProtocol] = [A(), B()]

func someFunc<T: ItemProtocol>(items: [T]) {
for item in items {
print(item.message)
}
}

// Everything compiles fine until this
someFunc(items: items)

This is a frequent pain point: protocol existentials cannot stand in for the protocol they represent.
Your function wants a concrete type that conforms to ItemProtocol, but an array of disparate types which happen to separately conform to ItemProtocol does not do that.

You will need to overload thusly:

func someFunc(items: [ItemProtocol]) {
  for item in items {
    print(item.message)
  }
}

until, someday, this pain point is resolved.

Cheers,
Guillaume Lessard

···

On Mar 9, 2017, at 12:46, Edward Connell via swift-users <swift-users@swift.org> wrote:

// Everything compiles fine until this
someFunc(items: items)

Worth mentioning that @objc protocols do conform to themselves as long as they do not have static methods or initializer requirements. However this may be too heavy-handed if a simple overload can do the trick.

Slava

···

On Mar 9, 2017, at 1:10 PM, Guillaume Lessard via swift-users <swift-users@swift.org> wrote:

On Mar 9, 2017, at 12:46, Edward Connell via swift-users <swift-users@swift.org> wrote:

// Everything compiles fine until this
someFunc(items: items)

This is a frequent pain point: protocol existentials cannot stand in for the protocol they represent.
Your function wants a concrete type that conforms to ItemProtocol, but an array of disparate types which happen to separately conform to ItemProtocol does not do that.

You will need to overload thusly:

func someFunc(items: [ItemProtocol]) {
for item in items {
   print(item.message)
}
}

until, someday, this pain point is resolved.

Cheers,
Guillaume Lessard

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users