无法将结果 <Bool, Error> 转换为预期的条件类型 'Bool'。 Swift

Cannot convert Result<Bool, Error> to expected condition type 'Bool'. Swift

如何仅在 Swift 中将 Result<Bool, Error> 的结果作为 Boolean 答案?

我从 AppStore 购买 ViewController:

Purchases.default.purchaseProduct(productId: "com.justdoit.buy_1week") { [weak self] res in
   self?.hideSpinner()
   if res == .success {
     // Handle result

     // IF OKAY - WE DO THE REQUEST AND CHANGE EVERYTHING FOR PREMIUM USER

   } else {
     self?.alert(alertMessage: "Error during the purchase") // my popUp view
   }
}

Purchases.swift:

import StoreKit

typealias RequestProductsResult = Result<[SKProduct], Error>
typealias PurchaseProductResult = Result<Bool, Error>

typealias RequestProductsCompletion = (RequestProductsResult) -> Void
typealias PurchaseProductCompletion = (PurchaseProductResult) -> Void


// class
class Purchases: NSObject {
    
    static let `default` = Purchases()
    fileprivate var productPurchaseCallback: ((PurchaseProductResult) -> Void)?
    
    private let productIdentifiers = Set<String>(
        arrayLiteral:
            "com.justdoit.buy_1week",
            "com.justdoit.buy_1month",
            "com.justdoit.buy_3months",
            "com.justdoit.buy_1year"
    )
    private var products: [String: SKProduct]?
    private var productRequest: SKProductsRequest?

    func initialize(completion: @escaping RequestProductsCompletion) {
        requestProducts(completion: completion)
    }

    private var productsRequestCallbacks = [RequestProductsCompletion]()

    private func requestProducts(completion: @escaping RequestProductsCompletion) {
        guard productsRequestCallbacks.isEmpty else {
            productsRequestCallbacks.append(completion)
            return
        }

        productsRequestCallbacks.append(completion)

        let productRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
        productRequest.delegate = self
        productRequest.start()

        self.productRequest = productRequest
    }
    
    func purchaseProduct(productId: String, completion: @escaping (PurchaseProductResult) -> Void) {
        
        guard productPurchaseCallback == nil else {
            completion(.failure(PurchasesError.purchaseInProgress))
            return
        }
        
        guard let product = products?[productId] else {
            completion(.failure(PurchasesError.productNotFound))
            return
        }

        productPurchaseCallback = completion
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }

    public func restorePurchases(completion: @escaping (PurchaseProductResult) -> Void) {
        guard productPurchaseCallback == nil else {
            completion(.failure(PurchasesError.purchaseInProgress))
            return
        }
        productPurchaseCallback = completion
        // 4:
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

// responses
extension Purchases: SKProductsRequestDelegate {
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        guard !response.products.isEmpty else {
            print("Found 0 products")

            productsRequestCallbacks.forEach { [=14=](.success(response.products)) }
            productsRequestCallbacks.removeAll()
            return
        }

        var products = [String: SKProduct]()
        for skProduct in response.products {
            print("Found product: \(skProduct.productIdentifier)")
            products[skProduct.productIdentifier] = skProduct
        }
        self.products = products
        productsRequestCallbacks.forEach { [=14=](.success(response.products)) }
        productsRequestCallbacks.removeAll()
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Failed to load products with error:\n \(error)")
        productsRequestCallbacks.forEach { [=14=](.failure(error)) }
        productsRequestCallbacks.removeAll()
    }
}

extension Purchases: SKPaymentTransactionObserver {
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        // 1:
        for transaction in transactions {
            switch transaction.transactionState {
            // 2:
            case .purchased, .restored:
                if finishTransaction(transaction) {
                    SKPaymentQueue.default().finishTransaction(transaction)
                    productPurchaseCallback?(.success(true))
                } else {
                    productPurchaseCallback?(.failure(PurchasesError.unknown))
                }
            // 3:
            case .failed:
                productPurchaseCallback?(.failure(transaction.error ?? PurchasesError.unknown))
                SKPaymentQueue.default().finishTransaction(transaction)
            default:
                break
            }
        }

                productPurchaseCallback = nil
    }
}

extension Purchases {
    // 4:
    func finishTransaction(_ transaction: SKPaymentTransaction) -> Bool {
        let productId = transaction.payment.productIdentifier
        print("Product \(productId) successfully purchased")
        return true
    }
}

enum PurchasesError: Error {
    case purchaseInProgress
    case productNotFound
    case unknown
}

我第一次在 Swift 中处理付款,我不知道 如何只为成功付款获得 .success(true) 结果并在以后使用它...... 有什么建议吗?

使用开关盒。这里枚举有关联值。

Purchases.default.purchaseProduct(productId: "com.justdoit.buy_1week") { [weak self] res in
    switch res {
    case .success(let value):
        break
        
    case .failure(let error):
        print(error.lo)
        
    }
}

你也可以使用 if

if case Result.success(let value) = res {
   print(value)
} else if case Result.failure(let error) = res {
   print(error.localizedDescription)
}