HomeiOS Developmentios - Protocol extension's static perform can't be known as immediately in...

ios – Protocol extension’s static perform can’t be known as immediately in Swift


You can’t have an extension on existential varieties or metatypes. Since RLAction is a protocol, it isn’t attainable to write down RLAction.no matter(), because the token “RLAction” on this context is handled as an existential sort, any RLAction.

You would make RLAction a struct as an alternative, parameterised by some protocol implementation

// admittedly this isn't an excellent identify
protocol RLActionProtocol {}

struct RLAction {
    let impl: Impl
    
    static func run() -> RLAction the place Impl == RLCallbackAction {
        RLAction(impl: RLCallbackAction())
    }
}

struct RLCallbackAction: RLActionProtocol {}

Now the next all compiles:

let action1: RLAction = .run()
let action2 = RLAction.run()
func actionTaker(_ motion: RLAction) {
    
}
actionTaker(.run())

If you happen to don’t love that, I might recommend this different design, the place you declare the concrete RLAction varieties in a namespace, say RLActions.

protocol RLAction {}

extension RLAction the place Self == RLActions.Run {
    static func run() -> RLActions.Run {
        return RLActions.Run()
    }
}

enum RLActions {
    struct Run: RLAction {}
}

Then it’s attainable to do RLActions.Run(), which appears to be like much like RLAction.run().

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments