在Swift中实现特定协议的类的数组

时间:2015-02-18 21:40:36

标签: swift protocols

在实现协议的类数组上调用类方法时遇到问题。 Swift think数组包含协议,因此它会产生以下编译错误。

访问协议类型值'TransactionHandler.Type'的成员未实现。

我不想在数组中保存实际实例

protocol TransactionHandler {
    class func canHandleTransaction(transaction: SKPaymentTransaction) -> Bool
    func handleTransaction(transaction: SKPaymentTransaction)
}

class InAppPurchaseManager: NSObject, SKPaymentTransactionObserver {

    var handlers = [TransactionHandler.Type]()

    override init() {
        super.init()

        // TransactionHandler implementations
        // handlers.append(Product1TransactionHandler.self)
        // handlers.append(Product2TransactionHandler.self)
        // handlers.append(Product3TransactionHandler.self)
    }

    func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {

        for transaction in transactions {

            for handler in handlers {
                 // Don't want to save instances in the array, that's waste of memory
                 // Compile errors all over the place, can be run in playground
                if handler.canHandleTransaction(transaction as SKPaymentTransaction) {
                    let handlerInstance = handler()
                    handlerInstance.handleTransaction(transaction)
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:-1)

为什么用你的对象TransactionHandler的相同名称命名你的协议?

1 /后缀您的protocolName: TransactionHandlerProtocol TransactionHandlerDelegate

2 /和您的班级 TransactionHandler

编辑:对不起,我看得太快了

编辑2:

删除.Type

var handlers = [TransactionHandler]()

类的处理程序数组符合协议TransactionHandler