Honey Honey - 3 months ago 12
Swift Question

Why do I get the error “Protocol … can only be used as a generic constraint because it has Self or associated type requirements” mean?

I wrote an extension onto

Int
as below.

extension Int {
func squared () -> Int {
return self * self
}
}

print(10.squared()) // works


The above code works. Now I want to extend the
IntegerType
protocol so that Int, UInt, Int64, etc would all conform. My code is as below.

extension IntegerType {

func squared () -> IntegerType { // this line creates error

return self * self

}
}


I get error:


Protocol 'IntegerType' can only be used as a generic constraint because it has Self or associated type requirements


I already saw this question and its video & this question, still couldn't understand. I only understood that there is some
associatedType
which in this case is
Self
but couldn't connect the dots. I feel like also my lack of knowledge on the
Generics
subject is also a reason...

Can someone elaborate a bit on the subject and why does the extension create an error?

Answer

You just have to return Self

Swift 3

extension Integer {
    func squared() -> Self { 
        return self * self
    }
}

Swift 2.2.1

extension IntegerType {
    func squared() -> Self {
        return self * self
    }
}