5

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?

phbelov
  • 2,329
  • 3
  • 18
  • 15
  • You can use a enum with a integer rawValue, or use a property with a custom setter which will test the value and modify it if needed. – Michaël Azevedo Feb 05 '16 at 13:40

2 Answers2

10
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)
Surely
  • 1,649
  • 16
  • 23
0

But why are you trying to implement it. Swift by default does not allow to pass more or fewer arguments than defined on the definition of that function or class.

So if you have a simple function which takes just one argument, then no one can pass less or more than one argument while calling your function. And if he would try to do so then the swift compiler won't allow him/her to do so.

So logically the conclusion is you don't need to develop anything like that.

If your scenario is different then what I m thinking please let me know by adding comment or writing another question in a simpler or understandable way.

Jay Mehta
  • 1,511
  • 15
  • 20
  • Jay, you've misunderstood what I actually meant. I'm not talking about number of arguments that we're passing to the function, but about the values that these arguments can take. So, for example, we have a 'c' parameter that we're passing to our function. I want 'c' to only be 1, 2 or 3 and nothing else. If the value of 'c' is not 1, 2 or 3 we'd not run a function or handle an error message. – phbelov Feb 05 '16 at 18:49