Redeclaring members in an extension hides the original member *sometimes*. Why?

本小妞迷上赌 提交于 2019-11-30 05:30:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46123963/redeclaring-members-in-an-extension-hides-the-original-member-sometimes-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!