creditCard.validateCardReturningError(&error) 条带 iOS 集成

creditCard.validateCardReturningError(&error) in stripe iOS integration

我正在尝试使用 swift 将 Stripe 集成到 iOS 应用程序中。我不断从该行收到这些错误:creditCard.validateCardReturningError(&error) 错误 1:'_' 不可转换为 '() throws ->()' 错误 2:<> 不可转换为 'BooleanType'

  var error: NSError?
    if (creditCard.validateCardReturningError(&error)){
        var stripeError: NSError!
        Stripe.createTokenWithCard(creditCard, completion: { (token, stripeError) -> Void in
            if (stripeError != nil){
                println("there is error");
            }

根据您收到的错误消息,听起来您正在使用新的 Xcode 7 beta,因此是新版本的 Swift。这个新版本最有趣和最有争议的变化之一是 Apple 修改了错误处理的工作方式。实际上,Apple 现在已经通过 ErrorType 向 Swift 语言添加了第一个 class 异常,并且能够在类型级函数上进行标记,这些函数可能会在执行过程中引发错误。因此,您可以期望开始看到具有以下签名的函数:

func foo() throws -> Bar 

这表明函数 foo 将抛出异常或 return Bar 类型的对象。

您处理此类函数的方式是通过三个新关键字:do、try 和 catch(您可能熟悉许多其他流行语言中的 try-catch 习语)。实际上,目的是将可能异常的代码块包装在一个 do 中,以标记对可以用 try 抛出异常的函数的特定调用,最后,使用 catch 语句指示在发生异常时应该做什么具体例外。

对于您的情况,以下的修改版本应该有效:

do {
    try creditCard.validateCardReturningError()
    STPAPIClient.sharedClient().createTokenWithCard(
            creditCard,
            completion: { (token: STPToken?, stripeError: NSError?) -> Void in 
        self.createBackendChargeWithToken(token!, completion: completion)
    })
} catch {
    println("There was an error.")
}

请注意,Stripe 尚未正式发布 Beta 版 iOS SDK 的新版本,因此关于新异常类型的内容还不多,但我会密切关注Github 任何更新的回购。

无论如何,有关新 Swift 错误处理的更多信息,我强烈推荐博客 post 在 Big Nerd Ranch:https://www.bignerdranch.com/blog/error-handling-in-swift-2/。如果您还有其他问题,请告诉我!