7

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?

1
  • 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. Commented Feb 5, 2016 at 13:40

2 Answers 2

15
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)
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.