如何在实例中访问静态协议方法
@H_502_2@我有一个Contact列表,该联系人可以是继承自Contact和GroupStatus协议的FamilyContact
@H_502_2@我想从GroupStatus调用静态方法但是徒劳无功……
@H_502_2@这是我的代码
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 } }@H_502_2@我无法编译Contact.Type没有名为’isPrivate’的成员 @H_502_2@我怎么称呼它?如果我删除静态关键字,它会起作用,但我认为将其定义为静态更合乎逻辑. @H_502_2@如果我更换
let isPrivate = contact.dynamicType.isPrivate()@H_502_2@通过
let isPrivate = FamilyContact.isPrivate()@H_502_2@它工作,但我可以有超过1个子类 @H_502_2@如果我删除静态键盘,我可以这样做:
if let c = contact as? GroupStatus { if !c.isPrivate() { nonPrivateContact.append(contact) } }@H_502_2@但我想保留static关键字
解决方法
这看起来像一个错误或不受支持的功能.我希望如此
以下作品:
我目前唯一能想到的解决方法,也许有人来了
有更好的解决方案…… @H_502_2@Swift 2 / Xcode 7的更新:正如@Tankista在下面提到的,这有已修好.上面的代码在Xcode 7 beta 3中编译并按预期工作.
以下作品:
if let gsType = contact.dynamicType as? GroupStatus.Type { if gsType.isPrivate() { // ... } }@H_502_2@但是,它不编译:
error: accessing members of protocol type value 'GroupStatus.Type' is unimplemented@H_502_2@它使用FamilyContact.Type而不是GroupStatus.Type进行编译.这里报告了一个类似的问题: @H_502_2@> Swift 1.1 and 1.2: accessing members of protocol type value XXX.Type’ is unimplemented @H_502_2@使isPrivate()成为实例方法而不是类方法
我目前唯一能想到的解决方法,也许有人来了
有更好的解决方案…… @H_502_2@Swift 2 / Xcode 7的更新:正如@Tankista在下面提到的,这有已修好.上面的代码在Xcode 7 beta 3中编译并按预期工作.