Swift TIL 5

Posted on 2020-06-26 15:44 +0100 in TIL • 1 min read

I'm going to file this one under "it makes perfect sense, but I don't think it aids in making the code readable" -- something which I'm finding is a bit of a theme with Swift.

In Swift self gets used and gets used in a way you'd expect from many other languages. So far so good. But, it seems, Self is also a thing too, and it's different from self. Whereas self is the current instance, Self is the current type. So consider this:

class Greeting {

    class func message() -> String {
        "Ayup!"
    }

    func message() -> String {
        "Well hello there"
    }

    func emit() {
        print( Self.message() )
        print( self.message() )
    }
}

Greeting().emit()

When run, the output is:

Ayup!
Well hello there

It makes sense that that's the case. I actually really like the ability to use Self rather than having to use Greeting, but damn that's really setting things up for either mistyping or misreading code. You're going to want to hope that your development environment makes it super obvious what's a value and what's a type when it comes to using font choices.