7

By chance, I discovered that you can do this without the compiler complaining:

extension Date {
    var timeIntervalSinceNow: TimeInterval {
        return 1000
    }
}

What's weirder, is that this actually evaluates to 1000:

Date().timeIntervalSinceNow
  • The extension seems to hide the original member.

So I tried to do this with my own class:

class A {
    var a: String {
        return "A"
    }
}

extension A {
    var a: String {
        return "a"
    }
}
  • and it fails to compile: "invalid redeclaration of 'a'".

I observed that this does not affect the usage of the original member through a protocol, which is expected behaviour of hiding:

extension Date {
    var description: String {
        return "XXXX"
    }
}

let date: CustomStringConvertible = Date()
date.description // normal date

Date().description // "XXXX"

Can you explain why does the bullet pointed phenomena occur?

mfaani
  • 33,269
  • 19
  • 164
  • 293
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 2
    Could it be that `Date` is probably a wrapper around the old Objective-C `NSDate` while your class/extension `A` are pure Swift? – rmaddy Sep 08 '17 at 20:45
  • I tried to make `A` a subclass of `NSObject` and the same error appears, so I don't think that's the reason. @rmaddy – Sweeper Sep 08 '17 at 21:04
  • Modules. You can override like this across modules. No idea how to access the original member, though. – jscs Sep 08 '17 at 21:41
  • [Same class extension in two different modules](https://stackoverflow.com/questions/33534371/same-class-extension-in-two-different-modules) – jscs Sep 08 '17 at 21:44
  • @Sweeper: This is a bug, see matt's comment here: https://stackoverflow.com/questions/33862414/swift-override-function-in-extension/33862519?noredirect=1#comment79367406_33862519. – Martin R Sep 13 '17 at 16:15

1 Answers1

3

This works because you are declaring this extension in a separate module from the original variable declaration.

Across modules a variable name can be overloaded but in my mind this has been a shortcoming of Swift as there is currently no way to explicitly state which module declaration it is that you want.

Infinity James
  • 4,667
  • 5
  • 23
  • 36