1

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?

Hao Wu
  • 111
  • 6
  • 1
    This is essentially another version of [this](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself). Protocols just don't conform to other protocols. Use a constrained generic type instead. `` and `listener: T`. – Sweeper Sep 14 '20 at 02:30
  • Not related to your question but in your first method why not simply return `indexOfExactSameItem(searchingItem) != nil` ? The same in your second method you can simply return `firstIndex { $0 === searchingItem }` – Leo Dabus Sep 14 '20 at 03:50

1 Answers1

0

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

Dominic Frei
  • 327
  • 1
  • 5