0
protocol Cloner {
    func cloneSelf(thingBeingCloned t: Self) -> Self
}

final class Sheep : Cloner {
    func cloneSelf(thingBeingCloned t: Sheep) -> Sheep {
        let newSheep = Sheep.init()
        return newSheep
    }
}

If I take the keyword 'final' away before class Sheep, the compiler yells at me. I get the error:

method 'cloneSelf(thingBeingCloned:)' in non-final class 'Sheep' must return `Self` to conform to protocol 'Cloner'

Okay.. then I listen to that and I change the return value to Self instead of Sheep, then I get another error:

error: cannot convert return expression of type 'Sheep' to return type 'Self'
user7024499
  • 951
  • 1
  • 10
  • 24
  • Thanks. It was a good explanation. So my question now is, in the Sheep declaration, what is the difference between returning Self, and returning Sheep? – user7024499 Nov 26 '16 at 18:22
  • 1
    In a `final` class, there is no real difference as `Self` will always be `Sheep` – although it seems the compiler isn't quite smart enough to see that, so will tell you to use a return type of `Sheep`. You could also say `let newSheep = type(of: self).init()`, which would allow you to have a return of type `Self`, but again, this has no observable difference to what you're already doing, as `type(of: self)` will always return `Sheep.self`. – Hamish Nov 26 '16 at 18:28
  • Ah I see, so if I were to inherit that function to sayyyyyy... YellowSheep, then it would confuse the compiler because the contract of the promise from the protocol says that the parameter type and the return type MUST be the same, however the compiler knows that if I use Sheep in the parameter name, and self happens to be YellowSheep, then it breaks the protocol contract. Right? – user7024499 Nov 26 '16 at 18:49
  • I'm not sure I quite follow your exact logic, but yes if you had a `YellowSheep` subclass of `Sheep` and it didn't override `cloneSelf` with an implementation that returned a `YellowSheep`, then you're breaking the contract with the protocol – hence why the compiler wants you to make the class `final`. – Hamish Nov 27 '16 at 00:27

0 Answers0