2015-01-02 25 views
2

我已經超載了一個名爲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{...} 

回答

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