The curious case of the self in the night: #swiftlang

Swift infers self wherever you unambiguously refer to a type member. In the following snippet, I originally omitted a self reference before the contains function call after my delinting routine had caught it as unneeded. Nearly everyone I showed this to had kittens.

public var names: [String] {
    var nameArray = [String]()
    for (flagLessOne, string) in strings.enumerate() 
        where contains(Features(rawValue: 1<<(flagLessOne + 1))) {
        nameArray.append(string)
    }
    return nameArray
}

Their reaction was pretty much universal. “What contains? What the hell is this talking about?” This is a great example of where the reach of the language can produce a profound mismatch to developer comprehension and expectations. Although self isn’t required syntactically, pretty much no one could read the intent without it.

Adding the self back in fixed the comprehension and self-documentation issue and provided a terrific anecdote for the future.

for (flagLessOne, string) in strings.enumerate() 
    where self.contains(Features(rawValue: 1<<(flagLessOne + 1))) {
    nameArray.append(string)
}

Comments are closed.