phu
phu

Reputation: 1199

indexOf(Element) doesn't exist for [Foo.Type] arrays

Swift's CollectionType provides two indexOf methods: one that takes an element directly, and one that takes a predicate function. If I have an array of type [Foo.Type] (for any class Foo), the former doesn't exist; there's only the predicate version of indexOf. Why is this?

Upvotes: 1

Views: 265

Answers (1)

Jack Lawrence
Jack Lawrence

Reputation: 10772

The indexOf method that takes an element requires that the element must conform to the Equatable protocol. It's defined in a constrained protocol extension, so it only shows up when that constraint holds true.

Metatypes (of the form SomeType.Type) cannot themselves conform to protocols (current as of Swift 2.1). Therefore even though you can define an == operator at global scope that operates on metatypes, you can't actually have a metatype conform to the Equatable protocol. This is a known language limitation.

In some cases (e.g. when using types as keys in a dictionary) you may be able to use the standard library ObjectIdentifier type to work around this limitation.

Upvotes: 3

Related Questions