RayChen
RayChen

Reputation: 1468

What's differences between these protocol definition?

Recently, I'm a little confuse about the definition ways for protocol in swift.

protocol OneDelegate : class

or

protocol OneDelegate : NSObjectProtocol

or

@objc protocol OneDelegate

or

@class_protocol protocol OneDelegate

And shall we keep using weak for delegate? Or like unowned(unsafe) var dataSource: UITableViewDataSource?

Thanks for help!

Upvotes: 4

Views: 116

Answers (1)

Nathan Perry
Nathan Perry

Reputation: 300

The first and last are actually the same. Both specify that a protocol can only be adopted by a class, i.e. a struct can't adopt the protocol. The form protocol OneDelegate : class is preferred. And @class_protocol protocol OneDelegate is deprecated.

The second case is a way to extend an existing protocol. Say for example you wanted your UITableViewDelegate to respond to a long press, then you could define a protocol:

protocol UITableViewDelegateWithRecognizer: UITableViewDelegate {
    func longPressed()
}

Then conformance to the protocol UITableViewDelegateWithRecognizer requires conformance to all the UITableViewDelegate functions, plus the extra method longPressed.

You need to use @objc if you intend to use the protocol in a file written in Objective-C. Additionally if you want to have an optional function declaration you need to use @objc.

Finally the same ARC rules for memory management apply to Swift as Objective-C, thus you will often want to use the weak specifier. One caveat is that a lot of Swift objects are value types, not reference types. And you cannot have a weak reference to a value type. So if you need to use a weak reference to avoid a retain-cycle, then you must specify that the protocol is a class protocol, i.e. your first example.

Upvotes: 4

Related Questions