Redeclaring members in the extension hide the source element * sometimes *. What for?

By chance, I discovered that you can do this without a compiler complaint:

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

What is weirder is that this is actually evaluated to 1000:

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

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 he cannot compile: "incorrect override of" a ".

I noticed that this does not affect the use of the source element through the protocol, the expected hide behavior:

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

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

Date().description // "XXXX"

Can you explain why the events marked by bullets occur?

+4
source share
1 answer

, .

, , , Swift, , .

+1

Source: https://habr.com/ru/post/1685327/


All Articles