Petri
Petri

Reputation: 1028

Swift: Overloaded == operator being used on another type

I have overloaded the "==" operator for a class called PBExcuse, but when trying to compare EKSourceType objects the compiler tries to use my PBExcuse overloaded operator and won't compile. The error message is: "'EKSourceType' is not convertible to 'PBExcuse'".

Here is the applicable code: Where Comparing:

for (var i = 0; i < eventStore.sources().count; i++) {
        let source:EKSource = eventStore.sources()[i] as EKSource
        let currentSourceType:EKSourceType = source.sourceType
        let sourceTypeLocal:EKSourceType = EKSourceTypeLocal
        if (currentSourceType == sourceTypeLocal){ //something is wrong here!!
            calendar.source = source;
            println("calendar.source \(calendar.source)")
            break;
        }
}

In PBExcuse.swift:

func == (left:PBExcuse, right:PBExcuse) -> Bool{
    if (left.event == right.event && left.title == right.title && left.message == right.message){
       return true
    }
    return false
}

final class PBExcuse:NSObject, NSCoding, Equatable, Hashable{...}

Upvotes: 2

Views: 184

Answers (1)

Martin R
Martin R

Reputation: 539685

EKSourceType is a struct

struct EKSourceType {
    init(_ value: UInt32)
    var value: UInt32
}

so you can only compare its value property:

if (currentSourceType.value == sourceTypeLocal.value) { ... }

The compiler message is misleading. Since == is not defined for EKSourceType, the compiler tries to convert the struct to some other type for which == is defined. Without your custom PBExcuse class, the error message would be

'EKSourceType' is not convertible to 'MirrorDisposition'

Note that you can simplify the loop slightly to

for source in eventStore.sources() as [EKSource] {
    if source.sourceType.value == EKSourceTypeLocal.value {
        // ...
    }
}

Upvotes: 2

Related Questions