Lawrence413 Lawrence413 - 5 months ago 12
Swift Question

Swift Class Custom Type Property

I am having trouble with Swift class properties and I have no idea what to search.

I want to create something like this:

defenceSystem.status = status.online
defenceSystem.status = status.offline
defenceSystem.status = status.destroyed


So basically I want the
status
property (or class; not sure what it should be) to have 3 values:
online
,
offline
and
destroyed
.

But I want those 3 properties to have a custom type, not String, Int or anything else. Basically I don't want them to store anything. Just to act like flags.

I thought that I should write something like this:

class defenceSystem {
class status {
// Declare the 3 status types
}
var status = status()
defenceSystem.status = status.online
}


I tried just writing
var online
but Xcode says it requires a type.

Answer

You can make use of an enum to hold the three different states. E.g.

class DefenceSystem {
    enum Status {
        case Online
        case Offline
        case Destroyed
    }

    var status: Status

    init(status: Status) {
        self.status = status
    }
}

let defenceSystem = DefenceSystem(status: .Online)

print(defenceSystem.status) // Online
defenceSystem.status = .Offline
print(defenceSystem.status) // Offline