[英]Swift Generics and Protocol Extensions
我有一個協議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之后)。
那是一個有趣的問題。 您的代碼似乎應該可以工作; 您可能要提交增強請求 。
這是一種似乎正常工作的解決方法:
class SomeGenericClass<CellType: Cell> {
func someFunction() {
let reuseIdentifier = (CellType.self as Reusable.Type).reuseId()
}
}
另一種(解決方法)獲得所需內容的方法:
class GenericExample<CellType:UITableViewCell where CellType:Reusable>
{
func test() -> String {
return CellType.reuseId()
}
}
GenericExample<UITableViewCell>().test() // returns "UITableViewCell"
GenericExample<MyCell>().test() // returns "MyCell"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.