Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to access the name variable from Indicator class, which inherits from Person. However, I believe I'm not doing my initialization right.

I get the following: 'error: instance member 'name' cannot be used on type 'Indicator'`.

class Person {
    var name: String

    init(myName: String){
        self.name = myName
    }

    deinit {
        Indicator.letKnowPersonDeinitialized()
    }
}


class Indicator: Person {
    convenience init() {
        self.init()
    }

    static func letKnowPersonDeinitialized() {
        print("(name)")
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot access non-static stuff directly in a static method.

The method letKnowPersonDeinitialized is static because it is modified with the static modifier:

static func letKnowPersonDeinitialized() {
  ^
  |
here!
}

The name property of Person is not static because it is not modified by static.

Since non-static members belong to each individual instance of that class and static members belong to the class itself, static members have no direct access to non-static members. They can only access non-static members when an instance is present.

To solve your problem, add a parameter to the letKnowPersonDeinitialized method:

static func letKnowPersonDeinitialized(person: Person) {
    print(person.name)
}

And in the deinitializer:

deinit {
    Indicator.letKnowPersonDeinitialized(self)
}

VERY IMPORTANT STUFF:

I don't think your code is designed well. This is not how you use inheritance.

Inheritance means "is a kind of". So if Indicator inherits from Person, it means that an indicator is a kind of person.

According to common sense, an indicator is not a person. Therefore, it is not suitable to use inheritance here. It makes little sense.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...