Snowman
Snowman

Reputation: 32071

Unable to create instance variable and class variable of the same name

The following code does not compile:

class object {
    class var myVar: String! {
        return "from class"
    }

    var myVar: String! {
        return "from instance"
    }
}

Error:

Invalid redeclaration of 'myVar'

Is this not possible with Swift or am I doing it wrong? This is totally legal in Objective-C (as functions rather than variables).

Upvotes: 3

Views: 904

Answers (1)

Undo
Undo

Reputation: 25697

Currently, you can't. If you really want to do this, you can file a Bug Report with Apple.

I would advise against doing this. It's really bad practice, simply because having two different variables named the exact same thing, the only difference being how they are accessed, is a terrible code smell. And it's confusing.

So file a radar if you want to, and then change your variable names. I doubt Apple will "fix" this.

Upvotes: 3

Related Questions