繁体   English   中英

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

[英]How to call static method provided by protocol in Swift

如何访问实例内的static协议方法

我有一个列表Contact ,联系人可以是FamilyContact从继承ContactGroupStatus 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关键字,它会起作用,但我认为将其定义为 static 更合乎逻辑。

如果我更换

let isPrivate = contact.dynamicType.isPrivate()

经过

let isPrivate = FamilyContact.isPrivate()

它有效,但我可以有 1 个以上的子类

如果我删除static键工作,我可以通过这种方式做到这一点:

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编译。 这里报告了一个类似的问题:

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

Swift 2 / Xcode 7 的更新:正如@Tankista 在下面提到的,这已经得到修复。 上面的代码在 Xcode 7 beta 3 中按预期编译和工作。

type(of: contact).isPrivate()

这应该适用于最近的 Swift。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM