Any potential problem with using typealias `Self` in final classes?

Since we don't have Self for final classes yet, I'm wondering if there is any disadvantage or danger in doing something like this as a temporary workaround:

final class Foobar {
    typealias `Self` = Foobar
}

final class Foo<Bar> {
    typealias `Self` = Foo<Bar>
}
2 Likes

Nothing to add, except that I have wondered the same.

1 Like

Let's be explicit: the "disadvantage or danger" that you foresee is a future version of the Swift language that comes with a built-in definition of Self for final classes. How would the conflict between your custom Self and the future language-level Self be handled? Could it make your code stop compiling, or change its behavior?

Given the code below compiles fine, I'd bet that you're safe:

struct Struct1 {
    // No Self definition: OK
    func foo(input: Self) {
        let local: Struct1 = input
    }
}

struct Struct2 {
    // Redundant Self definition: OK
    typealias `Self` = Struct2
    func foo(input: Self) {
        let local: Struct2 = input
    }
}

struct Struct3 {
    // Alternative Self definition: OK
    typealias `Self` = Int
    func foo(input: Self) {
        let local: Int = input
    }
}

final class Class1 {
    typealias `Self` = Class1
    func foo(input: Self) {
        let local: Class1 = input
    }
}

For maximum safety, register your code in the Swift Source Compatibility program.

2 Likes

By "disadvantage or danger", I was thinking more about whether there are potential conflicts or ambiguity in the current type system. Thank you for pointing out that compatibility with future versions of Swift should be considered as well. And sorry that I wasn't very clear in my question.

Thanks for the examples. I think likewise, that "typealias `Self`" should be safe. I just wanted to make sure I didn't miss anything.

For reference here is an existing bug report for this issue SR–11176.

It’s worth noting that the acceptance note for SE–68 “Expanding Swift Self to class members and value types” specifically mentions that final classes should be supported:

The core team has accepted the first half for this proposal. This allows the use of “Self” as shorthand for referring to the containing type (in the case of structs, enums, and final class) or the dynamic type (in the case of non-final classes).

Terms of Service

Privacy Policy

Cookie Policy