0

Would it be possible in Swift to write a function that takes an enum and an enum case and compare them?

Below is the example use case, how would you write isSameAction function?

protocol Action {}


enum CounterAction: Action {
    case IncrementBy(Int)
    case DecrementBy(Int)
}

enum LoadingAction: Action {
    case Loading, Loaded
}


let action1 = CounterAction.IncrementBy(1)
let action2 = CounterAction.DecrementBy(2)
let action3 = LoadingAction.Loaded

let actions:  [Action] = [action1, action2, action3]

actions.filter(action in isSameAction(action, CounterAction.IncrementBy))

1
  • 3
    Could you give more context on what exactly you're trying to achieve? Consider the Action protocol, what exactly is it supposed to do? Sure it lets you put instances of both CounterAction and LoadingAction into the same array, but you can't actually do much with that. It has no requirements of its conforming types, so similar to Any, the only thing you can really do with objects that conform to that protocol is to cast them to their concrete type, and use them like that. Commented Feb 13, 2021 at 16:43

1 Answer 1

2

You can use if case to check if your enumeration is CounterAction.IncrementBy and return true otherwise return false:

let filtered = actions.filter {
    if case CounterAction.IncrementBy = $0 { return true }
    return false
}
Sign up to request clarification or add additional context in comments.

Comments

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.