1

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?

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • possible duplicate of [Distinction in Swift between uppercase "Self" and lowercase "self"](http://stackoverflow.com/q/27863810) – jscs May 18 '16 at 18:48
  • I read that question and all of the answers without finding an answer to my specific question. I know exactly what `Self` refers to I even have *no problem* using `Self` as a method parameter within a protocol. My question is how can I use `Self` _in an expression_ in which I invoke a type method on it. Did I miss that answer in the referenced question? – Ray Toal May 18 '16 at 18:52
  • 1
    As far as I can see, it just boils down to "`Self` doesn't mean what you want it to mean", so the actual meaning of `Self` seems to be a relevant answer. – jscs May 18 '16 at 18:57
  • Ahhhh the key idea is _will conform to the protocol_ which makes no sense in an _extension_. TBH it's pretty opaque, but clear once pointed out. – Ray Toal May 18 '16 at 19:09

2 Answers2

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

In a static/class context, self refers to the type.

In a non-static context, you could use self.dynamicType..

Also note there is a proposal to allow Self to access type in non-static contexts (see https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md)

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • "In a static/class context, self refers to the type." -- I didn't know that, but it makes perfect sense. – Ray Toal May 18 '16 at 19:11
2

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

extension Int {
    static var allOnes: Int { return ~allZeros }
}
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Diogo Antunes
  • 2,241
  • 1
  • 22
  • 37
  • That's the right Swift idiom of course! Well done. But any idea why `~Self.allZeros` generates that error? It's as if we can use `Self` as a type specifier but not in an expression. – Ray Toal May 18 '16 at 18:54
  • The 'Self' expression is used inside a protocol (not an extension) and refers to the type that will conform to that protocol. – Diogo Antunes May 18 '16 at 19:04
  • 1
    _That's_ what I was looking for. Beautiful. – Ray Toal May 18 '16 at 19:10