When to use `protocol` and `protocol: class` in Swift?

user2636197 picture user2636197 · Oct 20, 2016 · Viewed 13.2k times · Source

I have setup a protocol to send some information back to the previous VC.

I define it like this:

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

But what is the difference when using:

protocol FilterViewControllerDelegate  {
        func didSearch(Parameters:[String: String]?)
    }

And when should I use a : class protocol?

Answer

Luca Angeletti picture Luca Angeletti · Oct 20, 2016

Swift 4 version

AnyObject added to a protocol definition like this

protocol FilterViewControllerDelegate: AnyObject  {
    func didSearch(parameters:[String: String]?)
}

means that only a class will be able to conform to that protocol.

So given this

protocol FilterViewControllerDelegate: AnyObject  {
    func didSearch(parameters:[String: String]?)
}

You will be able to write this

class Foo: FilterViewControllerDelegate {
    func didSearch(parameters:[String: String]?) { }
}

but NOT this

struct Foo: FilterViewControllerDelegate {
    func didSearch(parameters:[String: String]?) { }
}

Swift 3 version

:class added to a protocol definition like this

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

means that only a class will be able to conform to that protocol.

So given this

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

You will be able to write this

class Foo: FilterViewControllerDelegate {
    func didSearch(Parameters:[String: String]?) { }
}

but NOT this

struct Foo: FilterViewControllerDelegate {
    func didSearch(Parameters:[String: String]?) { }
}