Comparison of two delegate objects are the same instance

I am confused about comparing delegates. What I'm going to do is test two players to see if they are the same. But when I try to execute the code below, I get a compiler error that says "IPlayer does not convert to MirrorDisposition". What is the ideal way to validate delegates in Swift?

Here is my code:

var str = "Hello, playground"


protocol IPlayer{
    var x:Int {get set}
}

protocol IMatch{
    var ballOwner:IPlayer? {get set}
}


class Player:IPlayer{
    var x:Int = 5
}

class Match{
    var ballOwner:IPlayer?
}


var firstPlayer:protocol<IPlayer> = Player()
var secondPlayer:protocol<IPlayer> = Player()

//here is the problem !
if firstPlayer == secondPlayer {
   println("equal")
}


// if i check with reflection there is no error. But is it correct way?
var a = reflect(firstPlayer)
var b = reflect(secondPlayer)

if a.objectIdentifier == b.objectIdentifier {
    println("equal no error")
}

      

+3


source to share


2 answers


The operator is ===

used to check that two object references point to the same object. It is defined on two operands AnyObject

.

But it does not work immediately, because firstPlayer

and secondPlayer

are not objects. A protocol IPlayer

can also match structures and enumerations. To constrain it to objects, you must declare it as protocol IPlayer : class

.



ps protocol<IPlayer>

can be written as simple IPlayer

.

protocol IPlayer : class {
  var x:Int {get set}
}

class Player : IPlayer {
  var x:Int = 5
}

var firstPlayer:IPlayer = Player()
var secondPlayer:IPlayer = Player()

if firstPlayer === secondPlayer {
  println("equal")
} else {
  println("not equal") // prints "not equal" as expected
}

      

+8


source


The error "IPlayer does not convert to MirrorDisposition" means that the compiler could not find the == operator for IPlayer objects. To fix this, you can define it yourself, perhaps like this:

func == (left: IPlayer, right: IPlayer) -> Bool {
    return left.x == right.x
}

      



Then you can compare firstPlayer to secondPlayer without using reflexive.

0


source







All Articles