Can a function argument's type be a specific enum 'case'?

Viewed 111

Assuming we have an enum with associated values:

enum MyTimer {
    case describe(userId: String, 
                  endTime: Int)
    case vote(endTime: Int)
}

Can we define a function with a specific case of this enum as argument type, like:

func onDescribeTimerChange(timer: MyTimer.describe) {
    print(timer.userId)
}

This is the syntax I would use with a Kotlin sealed class because it makes it clear which case of the enum the function is designed for. But currently the Swift compiler rejects it with the message:

Enum case 'Describe' is not a member type of 'MyTimer'

2 Answers

The answer to your specific answer is no, as said by New Dev in their comment.

Note that Timer is a Foundation class, and you should avoid using that as an enum name.

You can only pass an Enum as a parameter, not its cases. So you can either write that function like this -

enum MyTimer {
    case describe(userId: String,
                  endTime: Int)
    case vote(endTime: Int)
}


func onDescribeTimerChange(timer: MyTimer) {
    switch timer {
    case let .describe(userId, endTime):
        print(userId, endTime)
    case .vote(let endTime):
        print(endTime)
    }
}


onDescribeTimerChange(timer: .describe(userId: "userID", endTime: 2))

Or you can use that as a method associated with your MyTimer enum type, like this -

enum MyTimer {
    case describe(userId: String,
                  endTime: Int)
    case vote(endTime: Int)
    
    func onDescribeTimerChange() {
        switch self {
        case let .describe(userId, endTime):
            print(userId, endTime)
        case .vote(let endTime):
            print(endTime)
        }
    }
}


MyTimer.describe(userId: "userID", endTime: 1).onDescribeTimerChange()
Related