I'm pretty new to swift, trying to get authorization from user.
to request multiple auth at once, I gathered multiple options as array, and trying to request.
let variableArray = [UNAuthorizationOptions.badge, UNAuthorizationOptions.alert]
// error: Cannot convert value of type '[UNAuthorizationOptions]' to expected argument type 'UNAuthorizationOptions'
try! await UNUserNotificationCenter.current().requestAuthorization(options: variableArray)
//these works.
try! await UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert])
try! await UNUserNotificationCenter.current().requestAuthorization(options: .badge)
so I checked requestAuthorization, and found this:
open func requestAuthorization(options: UNAuthorizationOptions = []) async throws -> Bool
I think it takes both UNAuthorizationOptions and [UNAuthorizationOptions] but compiler says
"hey, you are trying to pass
[UNAuthorizationOptions]but I needUNAuthorizationOptions!"
how can I append variableArray above code to requestAuthorization?
CodePudding user response:
This is because UNAuthorizationOptions conforms to the protocol OptionSet and an OptionSet can be initialised using an array literal, that is [...] which is something different than your variableArray which is an Array object.
So this is why you can do both
try! await UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert])
try! await UNUserNotificationCenter.current().requestAuthorization(options: .badge)
because one takes an UNAuthorizationOptions and the other one an OptionSet of UNAuthorizationOptions
You will find that this is quite a common pattern in swift when passing options or similar to functions in UIKit, AppKit, Foundation etc
CodePudding user response:
You need to explicitly specify the type of your variableArray as UNAuthorizationOptions. Replace variableArray with:
let variableArray: UNAuthorizationOptions = [UNAuthorizationOptions.badge, UNAuthorizationOptions.alert]
