Swift泛型和协议扩展

时间:2015-09-20 19:57:02

标签: swift generics protocols swift2 xcode7

我有一个协议Reusable,它有一个静态函数static func reuseId() -> String和一个协议扩展,它定义了该函数的默认实现。然后,我在UITableViewCell上实现了一个扩展,以符合Reusable协议。我现在可以在我的TableViewCells上使用该函数而不会出现问题:SomeTableViewCell.reuseId()

我遇到的问题是泛型。我有一个泛型类,它具有UITableViewCell类型的泛型参数:

internal class SomeClass<CellType: UITableViewCell>: NSObject { 
    ...
}

我希望能够在Reusable的泛型类中使用CellType中指定的函数,但不幸的是,这不能按预期工作。编译器始终生成错误Type 'CellType' has no member 'reuseId'

有人知道为什么会这样吗?有解决方法吗?

我正在使用Xcode 7.0和Swift 2.0。

来自德国的问候

更新:以下是一些示例代码,可以更好地显示我的问题:

import UIKit

protocol Reusable {
    static func reuseId() -> String
}

extension Reusable {
    static func reuseId() -> String {
        return String(self).componentsSeparatedByString(".").last!
    }
}

extension UITableViewCell: Reusable { }

class SomeGenericClass<CellType: UITableViewCell> {
    func someFunction() {
        let reuseIdentifier = CellType.reuseId()
    }
}

此代码将产生上述错误,但我不太明白为什么会发生这种情况。我认为 jtbandes 发布的示例代码的主要区别在于我使用的是静态函数。

更新:问题已在Xcode 8.3 beta 2中修复。上面的示例代码现在按预期工作(当然,在将其迁移到Swift 3之后)。

2 个答案:

答案 0 :(得分:0)

这是一个有趣的问题。你的代码看起来应该可行;你可能想要file an enhancement request

这是一个似乎正常工作的解决方法:

class SomeGenericClass<CellType: Cell> {
    func someFunction() {
        let reuseIdentifier = (CellType.self as Reusable.Type).reuseId()
    }
}

答案 1 :(得分:0)

获得所需内容的另一种(变通方法)方式:

class GenericExample<CellType:UITableViewCell where CellType:Reusable>     
{
    func test() -> String {
        return CellType.reuseId()
    }
}

GenericExample<UITableViewCell>().test() // returns "UITableViewCell"
GenericExample<MyCell>().test() // returns "MyCell"