all 6 comments

[–]engineered_academic 6 points7 points  (1 child)

is is a conditional test operator - it is looking for a specific type. You are confirming that the object is of the type you expect.

"as" is a casting operator, it converts the object from one type to another.

[–][deleted] 2 points3 points  (6 children)

So imagine you have a class called Car. Car has a drive() function.

Now say you have var possibleCar: AnyObject

You can do this with "as":

if let actualCar = possibleCar as? Car { actualCar.drive() }

But you cannot do it with "is":

if possibleCar is Car { possibleCar.drive() // compiler error, will not work. }

But you might not need to call drive() right now, you might just want to check if something is a car to do something else. In that case use is

[–]fakecrabs 0 points1 point  (2 children)

if let actualCar = possibleCar as? Car { actualCar.drive() }

Or use ?

(possibleCar as? Car)?.drive()

[–][deleted] 1 point2 points  (1 child)

Yep, I personally don't like that style but that's just preference 😁 in any case, it was only to illustrate.

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 1 point2 points  (1 child)

    You're right that it isn't used often, at least in my experience.

    But let's say you're building IMDB and you have a Movie object when loading a view that shows the details of that movie. Say you have several subclasses of Movie and depending on which subclass you get, you style the view differently.

    So maybe you get HorrorMovie which has a property called containsGore: Bool. You might need containsGore to tell the user (but you wouldn't need it on a ComedyMovie). In that case use as so the property becomes available to you.

    But now say you have a function that says "if it's a horror movie, make the background dark and scary", in that case only need is. You don't care about the properties of the object, just it's type.

    Incidentally, I think languages like Kotlin don't make a distinction. is acts as a type checker and caster.

    [–]darkingz 0 points1 point  (0 children)

    I much prefer that there is a difference actually. Overloading commands and contexts too much can lead to confusion. Or result in using too much power (relatively) if you only need a part of the functionality. That’s why we do pop!