在协议元类型Swift上不能使用静态成员

时间:2021-02-27 16:08:08

I'm trying to create a closure for a protocol type I have, but I'm getting the following error

我试图为我拥有的协议类型创建一个闭包,但是我得到了以下错误

Static member 'menuItemSorter' cannot be used on protocol metatype 'MenuItem.Protocol'

静态成员“menuItemSorter”不能用于协议元类型“MenuItem.Protocol”

Here's a reduced version of my code that I'm trying to run in a playground.

这是我试着在操场上运行的代码的简化版本。

protocol MenuItem {
    var order: Int {get}
}

extension MenuItem {
    static var menuItemSorter: (MenuItem, MenuItem) -> Bool {
        return { $0.order < $1.order }
    }
}

class BigItem : MenuItem {
    var order: Int = 1
}

let bigItems = [BigItem(), BigItem()]

let sorter = MenuItem.menuItemSorter

I'd like to be able to have a class/static var method on MenuItem that can sort menuItems, what's the best way to do this?

我想在MenuItem上有一个类/静态var方法可以对menuItems进行排序,最好的方法是什么?

1 个解决方案

#1


22  

Protocols don't have an accessible interface from the rest of your code.

协议没有可访问的接口从您的代码的其余部分。

You need to call it from an adhering type:

你需要从粘附类型中调用它:

class BigItem: MenuItem {
    var order: Int = 1
}

let sorter = BigItem.menuItemSorter

#1


22  

Protocols don't have an accessible interface from the rest of your code.

协议没有可访问的接口从您的代码的其余部分。

You need to call it from an adhering type:

你需要从粘附类型中调用它:

class BigItem: MenuItem {
    var order: Int = 1
}

let sorter = BigItem.menuItemSorter