Ray Toal Ray Toal - 6 months ago 11
Swift Question

How can I invoke a method on `Self` in a Swift extension?

When I try to evaluate this extension

extension Int {
static var allOnes: Int {return ~Self.allZeros}
}


I get


x.swift:2:38: error: use of unresolved identifier 'Self'
static var allOnes: Int {return ~Self.allZeros}


I can use lowercase
self
, though.

But
allZeros
is a type method, so I thought that
Self
should work. It looks silly to invoke a type method on an instance (though of course I know it makese sense). Why am I getting this error? Do I have to manipulate the value of
Self
somehow in my extension to get to work?

Answer

Since allZeros is already a method of Int you can just do it like this:

extension Int {
    static var allOnes: Int { return ~allZeros }
}