2017-02-17 2 views
2

Ich habe eine UIColor extension mit enummyColors genannt:wählt Zufallswert von Enum

enum myColors { 
    static let backgroundColor = UIColor(hex: "#373737") 
    static let strokeColor = UIColor(hex: "#FFFCF9") 
    static let red = UIColor(hex: "#FF6978") 
    static let green = UIColor(hex: "#BCE784") 
    static let blue = UIColor(hex: "#B1DDF1") 
    static let yellow = UIColor(hex: "#FFFD98") 
    static let purple = UIColor(hex: "#A09ABC") 
} 

Ich versuche, eine sprite Farbe zu setzen eine dieser Farben zufällig zu sein (rot, grün, blau, gelb, lila). Ich habe hier auf Stack Overflow einige Antworten gefunden, aber keine funktionierte. Ich habe versucht, es so zu tun:

let sprite = Player(x,y,color: myColors(rawValue: myColors.purple.rawValue+1) 

Aber es hat nicht funktioniert. Lila ist der letzte Punkt auf der Enum, also habe ich es gewählt.

Antwort

5

Ich schlage vor, vermeidet das Objekt UIColor innerhalb eines enum speichern, mein Ansatz:

enum myColors: String { 
    case backgroundColor = "#373737" 
    case strokeColor = "#FFFCF9" 
    case red = "#FF6978" 
    case green = "#BCE784" 
    case blue = "#B1DDF1" 
    case yellow = "#FFFD98" 
    case purple = "#A09ABC" 


    static func randomColor() -> UIColor { 
     let colorsToGetRandomly = [myColors.red, myColors.green, myColors.blue, myColors.yellow, myColors.purple] 
     let index = Int(arc4random_uniform(UInt32(colorsToGetRandomly.count))) 
     let color = colorsToGetRandomly[index].rawValue 
     return UIColor(hex: color) 
    } 
} 

myColors.randomColor() 
+1

Ihnen sehr danken. – swiftnewbie

4

Im Anschluss an @ Vadian Antwort, eine zufällige Farbe zurückzukehren ...

enum MyColors : String { 
    case background = "#373737" 
    case stroke = "#FFFCF9" 
    case red = "#FF6978" 
    case green = "#BCE784" 
    case blue = "#B1DDF1" 
    case yellow = "#FFFD98" 
    case purple = "#A09ABC" 

    private var uiColor : UIColor { 
     return UIColor(hex: self) 
    } 
    private var all: [UIColor] { 
     return [MyColors.background, .stroke, .red,… etc ] 
    } 

    var randomColor: UIColor { 
     let index = Int(arc4random_uniform(UInt32(all.count))) 
     return all[index].uiColor 
    } 

} 
+1

Danke, ich ging mit der ersten Antwort, aber danke für die Mühe :) – swiftnewbie

+0

Ich löschte meine Antwort, weil ich den * Random * Teil übersehen. – vadian

+0

"Aufzählungen dürfen keine gespeicherten Eigenschaften enthalten" –