I am struggling a bit with generics in Swift.
I have the following code:
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
}
}
The idea is to create a simple method that returns a new copy of a child instance with identical values. I don't want to write the constructor out for each Child classtype. (it has a lot of params in the real classes, and I like to keep it clean).
The error I get is:
cannot convert return expression of type 'Child' to return type T
Suggested solution is to make it return clone as! T. But that way I lose the reason to use a generic class.
Any idea how to solve this while keeping it generic and not write out the constructor in each class?