christophe
christophe

Reputation: 692

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

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!

Upvotes: 5

Views: 1380

Answers (3)

AstroCB
AstroCB

Reputation: 12367

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
}

Upvotes: 7

tikhop
tikhop

Reputation: 2087

as is an operator that cast a value to a different type.

For example:

Suppose you have an NSSet instance with some elements that have a type Car. Then if you want to get any object:Car from this set, you should call anyObject().

var someCar = set.anyObject() //here someCar is Optional with type AnyObject (:AnyObject?), because anyObject() -> AnyObject?

Let's imagine the situation when you need to get an object from the set with type Car.

var realCar: Car = someCar as Car //here realCar is Optional with type Car (:Car?)

Than if you exactly know that someCar is not an Optional ( someCar != nil) you can do follow:

var realCarAndNotAnOptional = someCar as Car! //here realCarAndNotAnOptional just have a type == Car

More info here: Swift: Type Casting

Upvotes: 2

Mark Pervovskiy
Mark Pervovskiy

Reputation: 1123

A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with the type cast operator (as).

from Swift Programming Language, Type Casting

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

It is not. It is trying to downcast to "Implicitly Unwrapped Optionals", see Swift Programming Language, Types

Upvotes: 2

Related Questions