从普通Swift函数到泛型函数

时间:2019-07-01 13:22:27

标签: swift generics

我有什么办法可以使下面的函数泛型?我多次尝试都失败了。特别是数组计数和'-1' 我还有另一个需要类似功能的课程。我没有重复代码,而是想到了创建通用函数。

class QAStorage {
   var myModelArray:[MyModelArray] = []
   var index:Int?


    private func nextIndex(for index: Int?) -> Int? {
        if let index = index, index < self.myModelArray.count - 1 {
            return index + 1
        }
        if index == nil, !self.myModelArray.isEmpty {
            return 0
        }
        return nil
    }

    func next() -> MyModelArray? {
        if let index = self.nextIndex(for: self.index) {
            self.index = index
            return self.myModelArray[index]
        }
        return nil
    }
}

这是我为nextIndex()创建通用函数的最后尝试。我收到错误Type 'T' has no member 'isEmpty'Use of unresolved identifier 'array'; did you mean 'Array'?

protocol Iterable {
var index:Int? { get set }
var count:Int { get }
var array:Array<Any> { get }
}

class IterableProtocol{

func nextIndex<T:Iterable> (for index:Int?) -> Int?{

    if let index = index, index < array.count {
        return index + 1
    }
    if index == nil, T.isEmpty {
        return 0
    }
    return nil
}
}

0 个答案:

没有答案