In Swift there is actually a protocol for enums called CaseIterable
that, if you add it to your enum, you can just reference all of the cases as a collection with .allCases
as so:
enum GeometryClassification: CaseIterable {
case Circle
case Square
case Triangle
}
and then you can .allCases
and then .randomElement()
to get a random one
let randomGeometry = GeometryClassification.allCases.randomElement()!
The force unwrapping is required because there is a possibility of an enum having no cases and thus randomElement()
would return nil
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…