Swift - Using as? operator

Introduction

The as? operator checks the type of a variable and returns an optional value of the specified type:

Demo

let person  : [String:Any] = ["name":"Jane","Age":26,"Tall":true] 
if let name = person["name"] { 
    var maybeString = name as? String 
    print(maybeString)/*  w  w  w.java  2  s.  c om*/
    // maybeString is an optional String containing "Jane" 
    var maybeInt = name as? Int 
    print(maybeInt)
    // maybeInt is an optional Int containing nil 
}

The as! operator works in the same way as the as? operator, except that it returns a nonoptional value of the specified type.

If the value can't be converted to the desired type, your program crashes:

Demo

let person  : [String:Any] = ["name":"Jane","Age":26,"Wears glasses":true] 
if let name = person["name"] { 
    var maybeString = name as! String 
    // maybeString is a String containing "Jane" 
}

Note

The as! operator is for when you're absolutely sure that the value you're converting is the right type.

And you don't want to work with optionals.

Related Topic