Lawrence413
Lawrence413

Reputation: 2016

Swift Class Property Of Another Property

I have a question. How can I declare a property of a property in a class? (Not sure if that's how it's called but that's the analogy I think of)

Example: dog.legs.count or lightSwitch.status.turnedOn

How do I declare count or turnedOn as properties of legs/status?

And as a matter of fact, of what types do I declare legs and status considering that count and turnedOn are Int, respectively Bool?

Upvotes: 2

Views: 137

Answers (2)

Wain
Wain

Reputation: 119031

It's not a great example of sensible composition, but:

class Legs {
    var count = 0
}

class Dog {
    var legs = Legs()
}

var dog = Dog()
dog.legs.count = 4

Upvotes: 3

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

It is completely up to you:

Just create a class Legs or Status and add a property count resp. turnedOn to it. Assign an instance of those classes to the owning class.

Of course, accessing it means to include Legs and Status in the owning class.

Upvotes: 3

Related Questions