Basically I'm using KVC, and have potentially different value types returned, and want to create a switch statement based on the type
I tried the answer here, but it wouldn't compile: Swift: Test class type in switch statement
var value: String = "Unknown"
switch node.value(forKeyPath: keyPath) {
case let numberValue is NSNumber:
if numberValue == 0 {
value = "No"
} else if numberValue == 1 {
value = "Yes"
}
case let stringValue is String:
value = stringValue
default:
break
}
it says
"Pattern variable binding cannot appear in an expression"
and
"Cast from <> to unrelated 'NSNumber' always fails"
This code here works for me:
var value: String = "Unknown"
let nodeValue = node.value(forKeyPath: keyPath)
switch nodeValue {
case is NSNumber:
if let numberValue = nodeValue as? NSNumber {
if numberValue == 0 {
value = "No"
} else if numberValue == 1 {
value = "Yes"
}
}
case is String:
if let stringValue = nodeValue as? String {
value = stringValue
}
default:
break
}
but it seems a little un-optimal that I need to use optional bindings to typecast a new variable
Is there a better way to do this?