Swift - Data Type Type Casting

Introduction

Swift is strongly typed.

Using the is and as operators, you can test for types as well as downcast.

You need to perform casting and type checks when dealing with variables of the Any type.

Any is often encountered in collections of mixed type.

For example, here we have a dictionary of type [String:Any]:

let person  : [String:Any] = ["name":"Jane","Age":26,"Wears glasses":true] 

Any lets you use any type inside a variable:

var anything  : Any = "hello" 
anything = 3 
anything = false 
anything = [1,2,3,4] 

You can use the is operator to check if an instance is of a certain class.

For example:

Demo

let person  : [String:Any] = ["name":"Jane","Age":26,"Wears glasses":true] 

let possibleString = person["name"] 
if possibleString is String { 
    print("\(possibleString!) is a string!") 
}

Result

Related Topic