2017-02-11 18 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 
    } 
} 
相關問題