ionic-team / capacitor

Build cross-platform Native Progressive Web Apps for iOS, Android, and the Web ⚡️
https://capacitorjs.com
MIT License
11.24k stars 955 forks source link

feat(ios): CAPPluginMethod selector-based initializer #7412

Open Steven0351 opened 1 month ago

Steven0351 commented 1 month ago

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.