2016-07-07 186 views
1

我遇到了Swift類屬性的問題,我不知道要搜索什麼。Swift類自定義類型屬性

我想是這樣創造的東西:

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

所以基本上我想要的status屬性(或類;不知道它應該是什麼)有3個值:onlineofflinedestroyed

但我希望這3個屬性具有自定義類型,而不是String,Int或其他任何東西。基本上我不希望他們存儲任何東西。只是爲了像旗幟一樣行事。

我認爲我應該寫這樣的事:

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

我試着只是寫var online但Xcode中說,它需要一個類型。

回答

3

您可以使用enum來保持三種不同的狀態。例如。

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 
0
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) 

    } 
} 

使用枚舉與定義的所有選項的狀態,然後創建枚舉的屬性,並設置在枚舉值,你需要的。

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html

我希望你的要求得到滿足。