JoeBayLD
JoeBayLD

Reputation: 999

Type variable in protocol - Swift 2

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(){
    }

}

Upvotes: 1

Views: 856

Answers (1)

TotoroTotoro
TotoroTotoro

Reputation: 17622

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
}

Upvotes: 0

Related Questions