Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a cast in a case pattern?

Tags:

swift

I have a switch case statement over an enum type with associated values in Swift:

enum Foo {
    case Something(let s: Any)
    // …
}

I would like to use a cast in the pattern match, a bit like this:

let foo: Foo = // …
switch foo {
    case .Something(let a as? SpecificType):
        // …
}

In other words, I would like the case pattern to succeed only if the cast succeeds. Is that possible?

like image 578
zoul Avatar asked Jan 07 '23 17:01

zoul


2 Answers

Your example basically works as is:

enum Foo {
  case Something(s: Any)
}

let foo = Foo.Something(s: "Success")
switch foo {
case .Something(let a as String):
  print(a)
default:
  print("Fail")
}

If you replace "Success" with e.g. the number 1 it will print "Fail" instead. Is that what you want?

like image 97
Michael Kohl Avatar answered Jan 14 '23 18:01

Michael Kohl


You can use where clause:

enum Foo {
    case Something(s: Any)
}

let foo: Foo = Foo.Something(s: "test")
switch foo {
case .Something(let a) where a is String:
    print("Success")
default:
    print("Failed")
}
like image 30
Greg Avatar answered Jan 14 '23 18:01

Greg