首页 文章

Swift泛型和协议扩展

提问于
浏览
0

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

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

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

我希望能够在 CellType 上的泛型类中使用 Reusable 中指定的函数,但不幸的是,这不能按预期工作 . 编译器始终生成错误 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

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

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

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

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

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

相关问题