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)//from  w w  w.ja  v  a  2  s  .c  o  m
    // 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