Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What function does "as" in the Swift syntax have?

Tags:

swift

Recently I stumbled upon a syntax I cannot find a reference to: What does as mean in the Swift syntax?

Like in:

var touch = touches.anyObject() as UITouch!

Unfortunately, it's hard to search for a word like as, so I didn't find it in the Swift Programming Language handbook by Apple. Maybe someone can guide me to the right passage?

And why does the element after as always have an ! to denote to unwrap an Optional?

Thanks!

like image 994
christophe Avatar asked Jan 14 '15 23:01

christophe


1 Answers

The as keyword is used for casting an object as another type of object. For this to work, the class must be convertible to that type.

For example, this works:

let myInt: Int = 0.5 as Int // Double is convertible to Int

This, however, doesn't:

let myStr String = 0.5 as String // Double is not convertible to String

You can also perform optional casting (commonly used in if-let statements) with the ? operator:

if let myStr: String = myDict.valueForKey("theString") as? String {
    // Successful cast
} else {
    // Unsuccessful cast
}

In your case, touches is (I'm assuming from the anyObject() call) an NSSet. Because NSSet.anyObject() returns an AnyObject?, you have to cast the result as a UITouch to be able to use it.

In that example, if anyObject() returns nil, the app will crash, because you are forcing a cast to UITouch! (explicitly unwrapping). A safer way would be something like this:

if let touch: UITouch = touches.anyObject() as? UITouch {
  // Continue
}
like image 140
AstroCB Avatar answered Sep 19 '22 05:09

AstroCB