Swift - Custom Type Comparing Structures

Introduction

You cannot compare two structures using the == operator.

This is because the compiler does not understand what defines two structures as being equal.

Hence, you need to overload the default meaning of the == and != operators:

enum StoneColor:String {
     case Black = "Black"
     case White = "White"
}

struct Chess {
    var row:Int              //0...7
    var column:Int           //0...7
    var color:StoneColor
}

func == (stone1: Chess, stone2: Chess) -> Bool {
    return  (stone1.row == stone2.row) &&
            (stone1.column == stone2.column) &&
            (stone1.color == stone2.color)
}

func != (stone1: Chess, stone2: Chess) -> Bool {
    return !(stone1 == stone2)
}

Here, the preceding two functions are overloading the two operators-equal == and not equal !=

Each function takes two Chess instances and returns a Bool value.

Two instances are deemed to be the same if the row , column , and color properties of each instance are equal to the other instance.

You can now use the == operator to test whether stone1 and stone2 are of the same value:

Demo

enum StoneColor:String {
     case Black = "Black"
     case White = "White"
}

struct Chess {/*from  w w w.  ja v a  2  s  .c o  m*/
    var row:Int              //0...7
    var column:Int           //0...7
    var color:StoneColor
    
   
}
func == (stone1: Chess, stone2: Chess) -> Bool {
        return  (stone1.row == stone2.row) &&
                (stone1.column == stone2.column) &&
                (stone1.color == stone2.color)
}
    
func != (stone1: Chess, stone2: Chess) -> Bool {
        return !(stone1 == stone2)
} 

var stone1 = Chess(row:12, column:16, color:StoneColor.Black)
var stone2 = Chess (row:12, column:16, color:StoneColor.Black)

if stone1 == stone2 {
    print("Same!")
} else {
    print("Different!")
}

Result

Related Topic