Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

swift - How to restrict a protocol to value types only?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...