This post is very much a case of me writing it down to try and get it all straight in my head, and to make sure it sticks. The other day I was reading about Swift's types and type-equality checks, and as I'd expect from plenty of other languages I've worked with, there's a way for checking that two types are the same, such that super/subclasses aren't taken into account, and a way where they are. So, given this silly code:
class Animal {}
class Cat : Animal {}
print( Cat.self == Animal.self ) // False
print( Cat.self is Animal.Type ) // True
print( type( of: Cat() ) is Animal.Type ) // True
it's made clear that ==
checks for strict equality and a super/subclass relationship isn't taken into account. On the other hand is
does take it into account.
Only... what's with this whole .self
sometimes and .Type
other times business? That took a little bit of writing code and playing to get comfortable with. Here's how I understand it now (and do feel free to correct me below if I'm way off):
Given the above code, Animal.Type
is the type of a value that expresses the type of Animal
. On the other hand, Animal.self
is a value that is the type of an Animal
. Yeah, I know, that still reads oddly. But written as code:
let feline : Cat.Type = Cat.self
I think it makes a lot more sense. And having got there I felt I better understood it. I'm not 100% sure I'm 100% with it, but I'm getting there.