如何将协议限制为仅值类型? [英] How to restrict a protocol to value types only?

查看:122
本文介绍了如何将协议限制为仅值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题,除了我不希望将协议仅限于类,我希望能够定义只能被枚举,结构等采用的协议.这可能吗?

Similar in spirit to this question, except, instead of limiting a protocol to only classes, I want to be able to define a protocol that can only be adopted by enums, structs etc.. Is this possible?

推荐答案

我找不到答案,但是通过反复试验,我得出了一个结论,那就是您找不到.为了将协议限制为仅类,您可以在其前加上class之类的

I couldn't find the answer, but through playing around, I've come to the conclusion that you can't. Being that to restrict a protocol to just classes, you precede it with class like

protocol SomeProto: class {
    func structYourStuff() -> Void
}

我假设在其他类型中这是一致的,

Making the assumption that this would be consistent among other types, I tried

protocol SomeProto: struct {
    func structYourStuff() -> Void
}

但是Xcode在同一行上给了我五个不同的错误,这使我得出结论:你做不到.不过我可能完全错了,我大约一个星期前才开始学习Swift

But Xcode gave me five different errors on one line, which brings me to the conclusion that you can't. I could be completely wrong though, I only started learning Swift about a week ago

这篇关于如何将协议限制为仅值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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