2017-02-11 17 views
0

我很困惑,因为我在两个ViewControllers之间传递了一个参数Notification。我不是尝试使用尽可能Bool传递给前进参数:来自Notification Dictionary Any或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'

那么,为什么在控制台中为statusAnytype(of: status))Bool。如果Any类型如何使用status作为Bool类型?

谢谢!

回答

1

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

如果你是负责通知和userInfo参数变化永远只是被迫施放价值Bool

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

尝试将它转换为Bool

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

你能做到在一个单一的step'if让状态= notification.userInfo![ “KEY0”]作为?布尔' – Russell

+0

是的问题更新,并感谢评论。 @Russell –

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 
    } 
} 
相关问题