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.

The first case is already matched. The second case will not be reached. Suppose that we had a non-matching case as the first case, as shown in the following example:

let anyValue: Any = 7 

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

In this scenario, the second case would be matched and cast anyValue to Int and bind it to ourValue, then we will be able to use ourValue in our statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset