简体   繁体   中英

Defining protocols in Swift

What are the differences between these three protocol definitions in Swift?

  1. protocol FooDelegate {}

  2. @objc protocol FooDelegate {} -- is this the same as protocol FooDelegate, NSObjectProtocol {} ?

  3. protocol FooDelegate: class {}

I'll deal with the cases in a slightly different order:

  1. A protocol can be adopted by an enum, a struct, or a class.

  2. protocol FooDelegate: class {} means that this protocol can be adopted only by a class.

  3. @objc protocol FooDelegate {} exposes this protocol to Objective-C - Objective-C can "see" it. It also implies (2), ie now this is a class protocol.

A good example of why you'd want to do (2) is when you want to declare a weak instance property typed as a protocol:

weak var delegate : MyDelegateProtocol

You can't say weak unless this thing is a class instance - not a struct or enum (since they do not have the same memory management). Declaring this protocol as a class protocol calms the fears of the compiler by telling it that whoever adopts this protocol will in fact be a class.

A good example of why you'd want to do (3) is that you want your protocol to have optional members. Only Objective-C can do that, so you effectively turn your protocol into an Objective-C protocol. And of course protocols defined in Objective-C are automatically seen by Swift as @objc protocols.

To add to matt's answer,

@objc protocol FooDelegate {} -- is this the same as protocol FooDelegate, NSObjectProtocol {}?

You mean protocol FooDelegate : NSObjectProtocol {} ? No. It doesn't extend NSObjectProtocol unless you explicitly declare it as such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM