2015-05-04 27 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'导致语法错误我。 –