I'm trying to figure out (if possible) how to pass the associated value of an enum to a function, and then switch over the type to execute some specific code.
This works in a playground:
struct Bar {}
struct Baz {}
enum Test {
case foo
case bar(value: Bar)
case baz(value: Baz)
}
func doSomething(value: Test) {
switch value {
case .foo: print("foo")
case .bar: print("bar")
case .baz: print("baz")
}
}
let bar = Bar()
doSomething(value: .bar(value: bar)) // prints "bar"
doSomething(value: .foo) // prints "foo"
But is it possible to pass the associated value directly as an argument? Something like this:
let bar = Bar()
doSomething(value: bar)
This of course fails because Bar
is not the same type as Test
.
How could I do that?
EDIT
For clarification, I am currently using overloading, but wanted to see if I could have one central public method which then dispatches to private methods based on the type of the associated value.
Just provide overloaded function
func doSomething(value: Bar) {
print("bar")
}
doSomething(value: bar) // now works !!
You can create a function that takes an Any
parameter and then try to figure out the type inside by having a switch on supported types but I am not sure it would be better than having separate functions for each type.
func doSomething(value: Any) {
switch value {
case is Test:
switch value as? Test {
case .foo:
print("foo")
default:
print("Not foo")
}
case is Bar:
print("bar")
case is Baz:
print("baz")
default:
print("Not supported")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.