How to restrict a protocol to value types only?

后端 未结 1 859
醉酒成梦
醉酒成梦 2020-12-17 16:09

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

相关标签:
1条回答
  • 2020-12-17 17:09

    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
    }
    

    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

    0 讨论(0)
提交回复
热议问题