O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type casting patterns

There are two types of casting patterns as follows:

  • is: This matches the type against the right-hand side of the expression
  • as: This casts the type to the left-hand side of the expression

The following example presents the is and as type casting patterns:

let anyValue: Any = 7 switch anyValue { case is Int: print(anyValue + 3) case let ourValue as Int: print(ourValue + 3) default: () } 

The anyValue variable is type of Any storing, an Int value, then the first case is going to be matched but the compiler will complain, as shown in the following screenshot:

We could cast anyValue to Int with as! to resolve the issue. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required