I have an enum, and I am trying to randomly return one of the members of the enum where each member can be given a frequencey of how often it is chosen (e.g. a member with a percentage of 0.05 would be returned 5% of the time).
I will post my best solution below, but I am hoping someone else has a better swift-2-ier way of doing it (e.g. filter/map/reduce, etc...), or a simpler solution.
Some notes:
- ListableEnum is a protocol which adds the allMembers() function in an extension (it returns an array of all members)
- init?(index:) is required by the ListableEnum to work its magic
- random() is added to Double via extension and it returns a Double between 0 and 1 (inclusive)
- I make an assumption that the frequencies add to 1.0
enum Test:Int,ListableEnum {
case A,B,C
init?(index:Int){self.init(rawValue:index)}
var frequency:Double {
switch self{
case .A: return 0.1 //10%
case .B: return 0.85 //85%
case .C: return 0.05 //5%
}
}
static var randomMember:Test{
let allM = Test.allMembers()
let rnd = Double.random()
var total = 0
for m in allM {
total += m.frequency
if total >= rnd {
return m
}
}
return allM.last!
}
}
Feel free to tell me I am being an ***** here (as long as it is accompanied by constructive feedback)