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

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

概述如何在实例中访问静态协议方法 我有一个Contact列表,该联系人可以是继承自Contact和GroupStatus协议的FamilyContact 我想从GroupStatus调用静态方法但是徒劳无功…… 这是我的代码 protocol GroupStatus { static func isPrivate() -> Bool // static method that indicate 如何在实例中访问静态协议方法

我有一个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中编译并按预期工作.

总结

以上是内存溢出为你收集整理的ios – 如何在Swift中调用协议提供的静态方法全部内容,希望文章能够帮你解决ios – 如何在Swift中调用协议提供的静态方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1108044.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存