2015-05-04 29 views
8

提供的靜態方法如何在實例中訪問static協議方法如何調用由協議斯威夫特

我有Contact列表,聯繫人可以是FamilyContactContact繼承和GroupStatus protocol

我想從GroupStatus卻徒勞無功調用靜態方法...

這裏是我的代碼

protocol GroupStatus { 
    static func isPrivate() -> Bool // static method that indicates the status 
} 

protocol IsBusy { 
    func wizzIt() 
} 

class AdresseBook { 

    private var contacts = [Contact]() 

    func addOne(c: Contact) { 
     contacts.append(c) 
    } 

    func listNonPrivated() -> [Contact]? { 

     var nonPrivateContact = [Contact]() 

     for contact in contacts { 
      // here is I should call the static method provided by the protocol 
      if self is GroupStatus { 
       let isPrivate = contact.dynamicType.isPrivate() 
       if !isPrivate { 
        nonPrivateContact.append(contact) 
       } 
      } 
      nonPrivateContact.append(contact) 
     } 

     return nonPrivateContact 
    } 
} 

class Contact : Printable { 

    var name: String 

    init(name: String) { 
     self.name = name 
    } 

    func wizz() -> Bool { 
     if let obj = self as? IsBusy { 
      obj.wizzIt() 
      return true 
     } 
     return false 
    } 

    var description: String { 
     return self.name 
    } 
} 

class FamilyContact: Contact, GroupStatus { 

    static func isPrivate() -> Bool { 
     return true 
    } 

} 

我無法編譯Contact.Type does not have a member named 'isPrivate'

我該怎麼稱呼它?它可以工作,如果我刪除static關鍵字,但我認爲更合理的定義它的靜態。

如果我更換

let isPrivate = contact.dynamicType.isPrivate() 

通過

let isPrivate = FamilyContact.isPrivate() 

它的工作原理,但我可以有超過1子

如果我刪除static keywork我可以這樣做:

if let c = contact as? GroupStatus { 
    if !c.isPrivate() { 
     nonPrivateContact.append(contact) 
    } 
} 

但我想保持static關鍵字

+0

您的實際問題是什麼?你期望的結果是什麼?你現在有什麼結果? – ABakerSmith

+0

我添加了錯誤。我無法編譯。 – thedjnivek

+0

我想打電話聯繫。isPrivate()'無論聯繫人的子類是什麼 – thedjnivek

回答

10

這看起來像一個錯誤或不支持的功能。我期望 了以下工作:

if let gsType = contact.dynamicType as? GroupStatus.Type { 
    if gsType.isPrivate() { 
     // ... 
    } 
} 

然而,這並不編譯:

 
error: accessing members of protocol type value 'GroupStatus.Type' is unimplemented 

編譯FamilyContact.Type,而不是GroupStatus.Type。類似的問題在這裏報道:

製作isPrivate()實例方法,而不是一類方法是 ,我目前能想到的唯一的解決方法,也許有人能 更好的解決方案...

Swift 2/Xcode 7的更新:由於@Tankista下面指出,這已經修復了 。上面的代碼在Xcode 7 beta 3中按預期進行編譯和工作。

+0

Thx,所以我必須等待Swift 1.3 :) – thedjnivek

+0

在swift 2.0中刪除'.dynamicType'並且它應該可以工作 –

+0

@Tankista:上面的代碼編譯並在Swift 2中工作。移除'.dynamicType'導致語法錯誤我。 –