Reputation: 2016
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.
Upvotes: 1
Views: 783
Reputation: 761
enum Status
{
case online
case offline
case destroyed
}
class defenceSystem:<Your Super class>
{
var status:Status
}
class ViewController: UIViewController {
override func viewDidLoad()
{
super.viewDidLoad()
let defence = defenceSystem();
defence.status = Status.online
print(defence.status)
defence.status = Status.offline
print(defence.status)
defence.status = Status.destroyed
print(defence.status)
}
}
Use the enumeration for the status with all option defined and then create a property of enumeration and set the value in enumeration as you needed.
I Hope your requirement is fulfilled.
Upvotes: 0
Reputation: 73186
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
Upvotes: 3