Используйте индекс (of :) для массива типа протокола в Swift - PullRequest
0 голосов
/ 24 августа 2018

Для большей гибкости внутри моих в основном статических табличных представлений у меня есть протокол, определенный следующим образом:

protocol StaticSection {
    static var active: [StaticSection] { get }
    // func cell(forRowAt indexPath: IndexPath, tableView: UITableView) -> UITableViewCell
    // var numberOfRows: Int { get }
}

extension StaticSection: Equatable {
    static func at(_ index: Int) -> StaticSection {
        return active[index]
    }

    static func index(ofSection section: StaticSection) -> Int {
        return active.index(of: section) // Not working :(
    }
}

, который я использую вот так

enum MySections: StaticSection {
    case header, footer, sectionA, sectionB

    static var active: [StaticSection] {
        // Here I can dynamically enable/disable/rearrange sections
        return [MySections.header, .footer]
    }
}

В реализации enumпротокола я могу получить доступ к индексу секции следующим образом:

(StaticSections.active as! [MySections]).index(of: .header)

Теперь я хочу реализовать index(ofSection section: StaticSection) в расширении, чтобы иметь более удобный способ сделать это.Я попробовал это, как показано выше в расширении.Но я получаю сообщение об ошибке:

Не удается вызвать 'index' со списком аргументов типа '(of: StaticSection)'

Возможно ли это даже в Swift?

1 Ответ

0 голосов
/ 24 августа 2018

Вы можете сделать что-то вроде этого:

protocol StaticSection {
    static var active: [Self] { get } // note the change to Self
    // func cell(forRowAt indexPath: IndexPath, tableView: UITableView) -> UITableViewCell
    // var numberOfRows: Int { get }
}

extension StaticSection where Self : Equatable { // another change here
    static func at(_ index: Int) -> Self {
        return active[index]
    }

    static func index(ofSection section: Self) -> Int? {
        return active.index(of: section)
    }
}

enum MySections: StaticSection {
    case header, footer, sectionA, sectionB

    static var active: [MySections] { // note the change to MySections
        // Here I can dynamically enable/disable/rearrange sections
        return [.header, .footer]
    }
}

Здесь важно отметить следующий синтаксис:

where Self : Equatable

Это означает, что расширение применяется только к типам, которые соответствуют StaticSection и Equatable, тогда как это:

: Equatable

сделает StaticSection наследуемым от Equatable, чего нельзя сделать в Swift.

...