Type variable in protocol - Swift 2

a 夏天 提交于 2019-12-13 02:52:14

问题


So I have a protocol, and in it I want a variable that is a class type. That way I can init that class from the variable.

Keep in mind that there will be many different classes. I made a quick example.

I get the error "type 'CashRegister' does not conform to protocol 'RegisterProtocol'"

This example isn't exactly what I'm doing, but it gets the point across. Thanks for the help.

protocol RegisterProtocol {
    var currentBill: DollarBillProtocol {get set}
    func makeNewBill()->DollarBillProtocol
}

extension RegisterProtocol {
    func printCurrentBill() {
        Swift.print(currentBill)
    }
}

class CashRegister: RegisterProtocol {

    var currentBill = OneDollarBill.self

    func makeNewBill() -> DollarBillProtocol {
        return currentBill.init()
    }
}



protocol DollarBillProtocol {
    // protocol that all bills have in common
}


class OneDollarBill: DollarBillProtocol {
    required init(){
    }
}

class FiveDollarBill: DollarBillProtocol {
    required init(){
    }

}

回答1:


The way you declare currentBill in CashRegister makes it a var of type class. But the protocol RegisterProtocol requires this variable to be of type DollarBillProtocol in any class that implements the protocol. The compile error is because of this mismatch.

To make this more clear, you could declare the var with the explicit type, as follows:

class CashRegister: RegisterProtocol {

    var currentBill: DollarBillProtocol = OneDollarBill() // or other initial value
}


来源:https://stackoverflow.com/questions/32858573/type-variable-in-protocol-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!