user842225
user842225

Reputation: 5979

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

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?

Upvotes: 9

Views: 3486

Answers (6)

marchinram
marchinram

Reputation: 5888

I would fix it by making the struct Equatable:

extension AdServiceType: Equatable {}

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

Upvotes: 4

Esqarrouth
Esqarrouth

Reputation: 39181

Just change it into class and nsobject and be over with the pain.

class MyClass: NSObject {

    //Write code in here
}

Upvotes: -3

Mario Zannone
Mario Zannone

Reputation: 2883

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.

Upvotes: 7

user842225
user842225

Reputation: 5979

I figured out that the simplest solution is to compare the value of struct 's property:

if aService!.serviceType.value == Normal.value {
   //DO SOMETHING.
}

Upvotes: 0

Sebastiran
Sebastiran

Reputation: 65

I do not have a lot of knowledge about your Thirdparty framework. But I know some types do not use '==' but .equals. For example:

if aService!.serviceType.equals(Normal)

Maybe that should do it.

Upvotes: -2

Saheb Roy
Saheb Roy

Reputation: 5957

I dont know swift but as far as i can understand Your struct is service type which is an object of type AdService> I think u need to get the variable inside the struct to make that operation as to giving an example

myStruct{
int x
int y
}

Now the condition would be valid for

myStruct obj1;
obj1.x = 50;
obj2.y = 40;

if(obj.x == obj.y) Something like this. You got to access the value inside the struct, not the struct itself. Or rather assign an && operator for (struct.x == struct2.x && struct.y == struct2.y) would pretty much represent values of struct == values of some other struct

Upvotes: 0

Related Questions