如何在swift3中使unwrap可选择优雅

时间:2016-12-23 02:33:50

标签: swift

guard let value = notification.userInfo?[Notification.BLEKey.value] as? Data,
        let packet = value.pt_hexString,
        let per = notification.userInfo?[Notification.BLEKey.peripheral] as? CBPeripheral,
        PTConnectManager.shared().currentPer == per
        else { return }

上面的代码可以工作,但很难读,是否有一些友好的解决方案?谢谢。

1 个答案:

答案 0 :(得分:1)

就我个人而言,我并不喜欢单个guard声明中包含的多个条款。在我看来,在多个guard语句中没有任何收获:

guard let value = notification.userInfo?[Notification.BLEKey.value] as? Data 
    else {return}
guard let packet = value.pt_hexString 
    else {return}
guard let per = notification.userInfo?[Notification.BLEKey.peripheral] as? CBPeripheral 
    else {return}
// ... and so on

我发现它更易读:它就像数据必须通过的一系列门。