Swift:重载==运算符在另一种类型上使用

时间:2015-01-02 09:10:51

标签: ios swift operator-overloading

我为一个名为PBExcuse的类重载了“==”运算符,但在尝试比较EKSourceType个对象时,编译器尝试使用我的PBExcuse重载运算符而不会编译。错误消息是:“'EKSourceType'不能转换为'PBExcuse'”。

以下是适用的代码: 比较的地方:

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;
        }
}

在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{...}

1 个答案:

答案 0 :(得分:2)

EKSourceType是一个结构

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

所以你只能比较它的value属性:

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

编译器消息具有误导性。由于==未定义EKSourceType, 编译器尝试将结构转换为某些其他类型,其中==已定义。 没有您的自定义PBExcuse类,错误消息将是

'EKSourceType' is not convertible to 'MirrorDisposition'

请注意,您可以将循环略微简化为

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