ios – 如何在Swift中调用协议提供的静态方法

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift中调用协议提供的静态方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在实例中访问静态协议方法

我有一个Contact列表,该联系人可以是继承自Contact和GroupStatus协议的FamilyContact

我想从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没有名为’isPrivate’的成员

我怎么称呼它?如果我删除静态关键字,它会起作用,但我认为将其定义为静态更合乎逻辑.

如果我更换

let isPrivate = contact.dynamicType.isPrivate()

通过

let isPrivate = FamilyContact.isPrivate()

它工作,但我可以有超过1个子类

如果我删除静态键盘,我可以这样做:

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

但我想保留static关键字

解决方法

这看起来像一个错误或不受支持功能.我希望如此
以下作品:
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进行编译.这里报告了一个类似的问题:

> Swift 1.1 and 1.2: accessing members of protocol type value XXX.Type’ is unimplemented

使isPrivate()成为实例方法而不是类方法
我目前唯一能想到的解决方法,也许有人来了
有更好的解决方案……

Swift 2 / Xcode 7的更新:正如@Tankista在下面提到的,这有已修好.上面的代码在Xcode 7 beta 3中编译并按预期工作.

原文链接:https://www.f2er.com/iOS/334814.html

猜你在找的iOS相关文章