Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operator ’==’ cannot be applied to two struct operands

Tags:

ios

swift

I am using a 3rd party framework, there is a file contains the following code:

struct AdServiceType {
    init(_ value: UInt)
    var value: UInt
}
var Internal: AdServiceType { get }
var Normal: AdServiceType { get }
var External: AdServiceType { get }

class AdService : NSObject {
   var serviceType: AdServiceType
   init!()
}

Then, in my own project class, I have

var aService : AdService?

//aService is initialised

//COMPILER ERROR: Binary operator ’==’ cannot be applied to two AdServiceType operands
if aService!.serviceType == Normal {
   //DO SOMETHING            
}

I got the compiler error mentioned above when I check if serviceType is Normal. Why? How to get rid of it?

like image 988
user842225 Avatar asked Sep 04 '15 11:09

user842225


Video Answer


2 Answers

The AdServiceType struct is not Equatable and cannot be used as a switch expression. But its value can. Try:

switch aService!.serviceType.value {
case Internal.value:
   //do something
case Normal.value:
   //do something
case External.value:
  //do something
default:
  ...
}

Alternatively, you can extend AdServiceType adding support for the Equatable protocol:

extension AdServiceType : Equatable {}
public func ==(lhs: AdServiceType, rhs: AdServiceType) -> Bool
{
    return lhs.value == rhs.value
}

and leave the switch as it is.

like image 132
Mario Zannone Avatar answered Sep 22 '22 02:09

Mario Zannone


I would fix it by making the struct Equatable:

extension AdServiceType: Equatable {}

func ==(lhs: AdServiceType, rhs: AdServiceType) -> Bool {
    return lhs.value == rhs.value;
}
like image 31
marchinram Avatar answered Sep 20 '22 02:09

marchinram