Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum With Integers in Swift

I'd like to know how can I limit the set of values that I can pass to function as an argument (or to class as a property). Or, in other words, the logic that I want to implement, actually, is to make function or a class accept only particular values. I've come up with an idea to use enum for it. But the caveat here is that I can't use pure integers with the 'case' like so:

enum Measure {
    case 1, 2, 3
}

Is there any way to implement what I want?

like image 986
phbelov Avatar asked Mar 14 '23 09:03

phbelov


1 Answers

enum Measure:Int{
    case ONE = 1
    case TWO = 2
    case THREE = 3
}

//accept it as argument
func myMethod(measure:Measure){
    switch measure {
        case .ONE:...
        case .TWO:...
        case .THREE
    }
}

//call the method with some raw data
myMethod(Measure(rawValue:1)!)
//or call the method with 
myMethod(Measure.ONE)
like image 142
Surely Avatar answered Mar 30 '23 08:03

Surely