我是swift的新手,尝试从用户那里获得授权。
为了一次请求多个auth,我收集了多个选项作为数组,并尝试请求。
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)
所以我检查了requestAuthorization
,发现了这个:
open func requestAuthorization(options: UNAuthorizationOptions = []) async throws -> Bool
我认为它需要UNAuthorizationOptions
和[UNAuthorizationOptions]
,但编译器说
"嘿,你想通过
[UNAuthorizationOptions]
,但我需要UNAuthorizationOptions
">
如何将上面的variableArray
附加到requestAuthorization?
这是因为UNAuthorizationOptions
符合协议OptionSet
,并且OptionSet
可以使用数组文字进行初始化,即[…],它与variableArray
(Array
对象)不同。
所以这就是为什么你可以同时进行
try! await UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert])
try! await UNUserNotificationCenter.current().requestAuthorization(options: .badge)
因为一个取UNAuthorizationOptions
,另一个取为UNAuthorizationOptions
的OptionSet
当传递UIKit、AppKit、Foundation等中的选项或类似功能时,您会发现这是swift中非常常见的模式
您需要将variableArray
的类型明确指定为UNAuthorizationOptions
。将variableArray
替换为:
let variableArray: UNAuthorizationOptions = [UNAuthorizationOptions.badge, UNAuthorizationOptions.alert]