Ryan
Ryan

Reputation: 4884

Swift operator "is"

According to the Apple's doc, checking type operator is "is".

I'm trying the bellows.

class BaseClass {
}

class SomeClass : BaseClass {
}

class OtherClass : BaseClass {
}

var s_ : SomeClass = SomeClass()

if(s_ is SomeClass) {
}


if(s_ is OtherClass) {
}

The compiler said 'is' test is always true for the first if statement, and 'OtherClass' is not a subtype of 'SomeClass'.

Why can't I compile this?

ADDED

This is the correct way to use is

var arr_ : [AnyObject] = Array<AnyObject>()
arr_.append(BaseClass())
arr_.append(SomeClass())
arr_.append(OtherClass())

for object in arr_  {
    if(object is SomeClass)
    {
        println("\(object) is SomeClass")
    }
    else
    {
        println("\(object) is not SomeClass")
    }
}

Upvotes: 1

Views: 194

Answers (2)

user2864740
user2864740

Reputation: 61875

Both of the statements are true and make sense because s_, as declared, must be an object of SomeClass.

Thus, _s is SomeClass is always true, because it must be an object of SomeClass. And, _s is OtherClass is always false because OtherClass is not a subtype of SomeClass as stated. Since these are provable mistakes the compiler prohibits the usage as such.

Now, change the code to var s_ : BaseClass = SomeClass() and note the different results.

With this change the value of s_ might not be an instance of SomeClass (as far as the compiler and type-system know), but it could be any object that conforms to BaseClass, including both SomeClass and OtherClass which are subtypes.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881463

What you're seeing makes perfect sense. It's akin to, using simple substitutions:

define shape
define square as subclass of shape
define circle as subclass of shape

s = square()
print (s is square) # yes, obviously.
print (s is circle) # no, not a chance.

Perhaps you meant that last one to be s is shape (or, in your case, s_ is BaseClass).

Upvotes: 0

Related Questions