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 need
UNAuthorizationOptions
!"
how can I append variableArray
above code to requestAuthorization?
2
Answers
You need to explicitly specify the type of your
variableArray
asUNAuthorizationOptions
. ReplacevariableArray
with:This is because
UNAuthorizationOptions
conforms to the protocolOptionSet
and anOptionSet
can be initialised using an array literal, that is […] which is something different than yourvariableArray
which is anArray
object.So this is why you can do both
because one takes an
UNAuthorizationOptions
and the other one anOptionSet
ofUNAuthorizationOptions
You will find that this is quite a common pattern in swift when passing options or similar to functions in UIKit, AppKit, Foundation etc