Hao Wu
Hao Wu

Reputation: 121

how to make protocol to conform another protocol in Swift?

I make a extension for Array where Elements are Object, so I can compare them by their address.

public extension Array where Element: AnyObject {
    func hasExactSameItem(_ searchingItem: Element) -> Bool {
        guard let _ = indexOfExactSameItem(searchingItem) else { return false }
        return true
    }
    func indexOfExactSameItem(_ searchingItem: Element) -> Int? {
        for (index, item) in self.enumerated() {
            if searchingItem === item {
                return index
            }
        }
        return nil
    }
}

There is another protocol conforming AnyObject protocol

public protocol IMServerListener: AnyObject {
    
}

I have a array containing IMServerListener

private var listeners = [IMServerListener]()

When I start adding listener to that array, the compiler complaining that '[IMServerListener]' requires that 'IMServerListener' conform to 'AnyObject'

func addListener(_ listener: IMServerListener) {
     listeners.hasExactSameItem(listener)
 }

I thought the IMServerListener is conforming the AnyObject protocol, so why did it happened?

Upvotes: 1

Views: 454

Answers (1)

Dominic Frei
Dominic Frei

Reputation: 422

I tried to construct a similar example in a playground:

import UIKit

protocol Foo: AnyObject {
    func foo()
}

protocol Bar: Foo {}

class A: Bar {
    func foo() {}
}

var bars = [Bar]()
bars.append(A())
bars.append(A())

bars[0] === bars[1] // equals operator used from AnyObject

Observations:
(1) Protocols can inherit from each other. If I leave out the implementation of foo() in class A it leads to a compiler error.
(2) Class A does inherit from AnyObject through Bar and Foo otherwise I could not use the equals operator.

To your question:
compiler complaining that '[compiler complaining that '[IMServerListener]' requires that 'IMServerListener' conform to 'AnyObject']' requires that 'IMServerListener' conform to 'AnyObject' sounds like there might be something wrong with the implementation of IMServerListener itself.

I am happy to extend my answer if you can show us this implementation / more code in general.

Cheers,
Dominic

Upvotes: 0

Related Questions