协议中的类型变量-Swift 2 [英] Type variable in protocol - Swift 2

查看:104
本文介绍了协议中的类型变量-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.

我收到错误消息类型'CashRegister'不符合协议'RegisterProtocol'"

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

}

推荐答案

CashRegister中声明currentBill的方式使其成为class类型的var.但是协议RegisterProtocol要求在实现该协议的任何类中,此变量的类型均为DollarBillProtocol.编译错误是由于这种不匹配造成的.

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.

为使这一点更加清楚,您可以使用显式类型声明var,如下所示:

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
}

这篇关于协议中的类型变量-Swift 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆