Is there a way to write this if
/else if
/else
ladder as a switch statement?
let x: Any = "123"
if let s = x as? String {
useString(s)
}
else if let i = x as? Int {
useInt(i)
}
else if let b = x as? Bool {
useBool(b)
}
else {
fatalError()
}
Here's my attempt:
switch x {
case let s where s is String: useString(s)
case let i where i is Int: useInt(i)
case let b where b is Bool: useBool(b)
default: fatalError()
}
It successfully chooses the right path, but s
/i
/b
are still of type Any
. The is
check doesn't have any effect in casting them. This forces me to force cast with as!
before usage.
Is there a way to switch on the type, and bind it to a name, all in one switch
statement?
case
. Just add aprint
and see you wont see any errors – Homophoneprint(_:)
has no problem handling parameters of typeAny
. Imagine the comments like//use s
are actually function calls that take a parameter of typeString
/Int
/Bool
, respectively. – Habitformingis
check doesn't have any effect in casting them" So if you really prints/i/b
then actually it prints the right value.print(s)
. I didn't knw about your functionuseString
. Thanks – Homophonefor thing in things
... – Negligee