Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Member Cannot Be Used on Protocol Metatype Swift

Tags:

ios

swift

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'

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?

like image 548
Alex Avatar asked Feb 27 '17 20:02

Alex


2 Answers

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
like image 97
GetSwifty Avatar answered Nov 14 '22 13:11

GetSwifty


You may consider using this approach as a workaround until Swift provides this feature:

class MenuItemFunctions {
    static var sorter: (MenuItem, MenuItem) -> Bool {
        return { $0.order < $1.order }
    }
}

let sorter = MenuItemFunctions.sorter
like image 1
Raunak Avatar answered Nov 14 '22 12:11

Raunak