我在Swift中使用泛型掙扎了一下。無法將類型'child'的返回表達式轉換爲返回類型T
我有以下代碼:
class Parent {
init(value: SomeThing) {
// ...
}
func clone<T: Parent>() -> T {
return T(value: SomeThing)
}
}
class Child : Parent {
var otherValue: SomeThingElse?
override func clone<T>() -> T where T : Parent {
let clone: Child = super.clone()
clone.otherValue = self.otherValue
return clone //ERROR: cannot convert return expression of type 'Child' to return type T
}
}
的想法是創建一個返回具有相同值的子實例的新副本的簡單方法。 我不想爲每個Child classtype寫出構造函數。 (它在真實課程中有很多參數,我喜歡保持它的清潔)。
我得到的錯誤是: cannot convert return expression of type 'Child' to return type T
建議的解決方案是讓return clone as! T
。但這樣我就失去了使用泛型類的理由。
任何想法如何解決這個問題,同時保持它的通用性,而不是寫出每個類中的構造函數?
你應該考慮使用值類型('struct')。值類型在賦值時被複制,因此您不必手動執行。你將失去繼承的能力,但你可以使用協議和擴展來解決這個問題。 – Palle
謝謝,但我不能使用結構,因爲類也需要在Objective-C中使用。 – Peterdk
如果你的類是一個NSObject子類,你可以使用[NSCopying](https://developer.apple.com/reference/foundation/nscopying)。 – Palle