来自通知字典Any或Bool的参数?

时间:2017-02-11 11:12:36

标签: swift dictionary boolean

我很困惑,因为我在两个ViewControllers之间传递Notification参数。我尝试使用传递为Bool的参数继续前进:

func doWhenParameterSelected(notification: Notification) {

    let status = notification.userInfo!["key0"]!
     print(type(of:status)) //is "Bool" in Console
     print(status) // value is "true" or "false" in Console

    if status {... // error occurs "'Any' is not convertible to 'Bool'"

我总是收到错误消息'Any' is not convertible to 'Bool'

那么,为什么status Any当控制台中的type(of: status))Bool时。如果Any键入如何将status用作Bool类型?

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试将其转换为Bool

let status = notification.userInfo!["key0"] as? Bool ?? false

答案 1 :(得分:1)

userInfo参数定义为[AnyHashable : Any](未指定的Dictionary),无论您发送的是什么。

如果您对通知负责,userInfo参数永远不会更改,只需将值强制转换为Bool

let status = notification.userInfo!["key0"] as! Bool

答案 2 :(得分:1)

在将其用作条件之前,您必须将其投射到Bool。

func doWhenParameterSelected(notification: Notification) {

    guard notification.userInfo?["key0"] as? Bool ?? false else {
        // could not cast to Bool or it was false
        return
    }

    // ...
}

<强> OR

func doWhenParameterSelected(notification: Notification) {

    if notification.userInfo?["key0"] as? Bool ?? false {
        // ...
    } else {
        // could not cast to Bool or it was false
    }
}