capacitor icon indicating copy to clipboard operation
capacitor copied to clipboard

feat(ios): CAPPluginMethod selector-based initializer

Open Steven0351 opened this issue 1 year ago • 0 comments

Add secondary initializer for CAPPluginMethod that takes a selector. Creates a convenience initializer as well with a Swift enum to avoid having to rely on global string values in the style of CAPPluginReturnPromise. For a pure Swift plugin implementation, it makes the definition potentially go from:

class MyPlugin: CAPPlugin, CAPBridgedPlugin {
  let pluginMethods: [CAPPluginMethod] = [
    .init(name: "promiseMethod", returnType: CAPPluginReturnPromise),
    .init(name: "callbackMethod", returnType: CAPPluginReturnCallback)
  ]

  @objc func promiseMethod(_ call: CAPPluginCall) {}
  @objc func callbackMethod(_ call: CAPPluginCall) {}
}

to this:

class MyPlugin: CAPPlugin, CAPBridgedPlugin {
  let pluginMethods: [CAPPluginMethod] = [
    .init(#selector(promiseMethod)),
    .init(#selector(callbackMethod), returnType: .callback)
  ]

  @objc func promiseMethod(_ call: CAPPluginCall) {}
  @objc func callbackMethod(_ call: CAPPluginCall) {}
}

A benefit of this approach include removing the need to stringify the name of the function. This will also validate the selector at compile time, so if it has not been annotated with @objc it will be a compiler error.

Steven0351 avatar Apr 18 '24 22:04 Steven0351