可选类型'PKPaymentAuthorizationViewController?'的值必须解开

时间:2019-06-07 03:31:04

标签: ios swift react-native applepay xcode10.2

当我尝试在ApplePay的代码块下方编译适用于iOS的react-native应用

    let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
    applePayController.delegate = self
    let rootViewController:UIViewController? = UIApplication.shared.delegate?.window??.rootViewController!
    rootViewController!.present(applePayController, animated: true, completion: nil)

抛出运行时错误。

Value of optional type 'PKPaymentAuthorizationViewController?' must be unwrapped to refer to member 'delegate' of wrapped base type 'PKPaymentAuthorizationViewController'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

PKPaymentAuthorizationViewController具有失败的初始化程序-也就是说,如果用户无法付款,则初始化程序将返回nil

这意味着applePayController是一个可选的-它可能包含nil,因此正如错误所述,您需要先打开可选的包装,然后才能访问该属性; applePayController?.delegate = self。更好的方法是使用if letguard let

例如:

if let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request), 
   let rootViewController = UIApplication.shared.delegate?.window??.rootViewController {
    applePayController.delegate = self
    rootViewController.present(applePayController, animated: true, completion: nil)
} else {
    // Payment is unavailable - handle this as appropriate
}

当Swift可以推断类型时,无需指定类型。最好也避免强制展开可选内容。