Zonily Jame
Zonily Jame

Reputation: 5359

Use `self` as a default parameter on static/class methods

Is there a way to set self as a default parameter on static methods? For example

enum Foo {
    static func processSomething(forOwner owner: Any = self) -> Bar {
        ...
    }

    // or 
    static func processSomething(forOwner owner: Any = Caller.self) -> Bar {
        ...
    }
}

I found this SO post but the question is about instance methods and I thought it might be possible for static/class methods because might be different.

This is so I can shorten codes like this for example

class Baz {
    var bar: Bar?

    func triggerSomething() {
        // automatically infer self instead of me explicitly placing it here
        // so the code will be this
        self.bar = Foo.processSomething()

        // instead of this
        self.bar = Foo.processSomething(forOwner: self)
    }
}

Edit: I'm actually just asking out of curiosity. I don't have a use case for this, and probably wouldn't use it in a real world scenario.

Upvotes: 1

Views: 184

Answers (2)

par
par

Reputation: 17724

self as a reference to an instance isn't available to static functions, so the answer to your question is "no" as far as that specific way. In the context however of saving yourself some typing, and by going through an instance method called triggerSomething() where self is available, you can accomplish what you're looking to do.

This answer is purely for the sake of addressing how you might go about doing this. I should say I honestly think there isn't a lot of utility in it, and if you find yourself needing a pattern like this you'd probably be better off investing more time in your design. But anyhoo, here's what this could look like.

Note that I'm returning an Int where you have Bar in your question for the sake of simplicity.

protocol Processable { }

class Foo: Processable {
    static func processSomething(forOwner owner: Processable) -> Int {
        return 1
    }

    func triggerSomething(forOwner owner: Processable? = nil) -> Int {
        return Foo.processSomething(forOwner: owner ?? self)
    }
}

Upvotes: 2

Chris Shaw
Chris Shaw

Reputation: 1610

No. For a static function, there is no 'self' it can use.

I don't understand why you'd need it; you can remove the parameter and call self.processSomething or other.processSomething as appropriate. Maybe you should explain why you think it would be useful for your situation, and think if it makes sense.

Upvotes: 1

Related Questions