12

I want to implement a protocol with a class method that takes an array of the implementing class as a parameter. For instance something like this:

protocol MyProtocol {
    static func foo(verticies: [Self]) -> Int
}

class MyClass : MyProtocol {
    class func foo(verticies: [MyClass]) -> Int {
        return 42
    }
}

When I attempt this, I get the following error:

Protocol 'MyProtocol' requirement 'foo()' cannot be satisfied by a non-final 'MyClass' class because it uses 'Self' in a non-parameter, non-result type

But this works perfectly if I use an object of type MyClass rather than an array:

protocol MyProtocol {
    static func foo(verticies: Self) -> Int
}

class MyClass : MyProtocol {
    class func foo(verticies: MyClass) -> Int {
        return 42
    }
}

Why doesn't this work for an array type, and is there a correct way to do this?

dfrib
  • 70,367
  • 12
  • 127
  • 192
sak
  • 2,612
  • 24
  • 55
  • I neglected to replace the type for the parameter of the function to 'MyClass' from 'Vertex' (I generalized the code to make it easier to understand for SA) - I've edited it to correct the error. – sak Oct 26 '16 at 19:05
  • Your code never compiled in any case because you said `-> Int1` but didn't return an Int. Don't make up stuff. Paste real code from Xcode into the browser. – matt Oct 26 '16 at 19:06

1 Answers1

10

The problem has to do with the indeterminate nature of what would happen if MyClass had a subclass (because generics, such as Array, are not classes and don't magically do polymorphism). Just do what the error message says, and all will be well:

protocol MyProtocol {
    static func foo(verticies:[Self]) -> Int
}
final class MyClass : MyProtocol {
    class func foo(verticies:[MyClass]) -> Int {
        return 1
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    [This workaround](https://stackoverflow.com/questions/37141067/a-swift-protocol-requirement-that-can-only-be-satisfied-by-using-a-final-class?rq=1) is one approach to solve this without making the class `final` – Shubham May 22 '18 at 22:50