我對 swift 很陌生,試圖從用戶那里獲得授權。
為了一次請求多個身份驗證,我收集了多個選項作為陣列,并嘗試請求。
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?
uj5u.com熱心網友回復:
這是因為UNAuthorizationOptions符合協議OptionSet,并且OptionSet可以使用陣列文字來初始化,即 [...] 這與您variableArray的Array物件不同。
所以這就是為什么你可以同時做
try! await UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert])
try! await UNUserNotificationCenter.current().requestAuthorization(options: .badge)
因為一個取一個UNAuthorizationOptions,另一個取OptionSet一個UNAuthorizationOptions
你會發現在傳遞選項或類似于 UIKit、AppKit、Foundation 等中的函式時,這是 swift 中相當常見的模式
uj5u.com熱心網友回復:
您需要明確指定variableArrayas的型別UNAuthorizationOptions。替換variableArray為:
let variableArray: UNAuthorizationOptions = [UNAuthorizationOptions.badge, UNAuthorizationOptions.alert]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497958.html
上一篇:視覺套件中人臉檢測中的模糊人臉
下一篇:重構陣列元素的位置
