In an attempt to circumvent the dreaded Self error when implementing a protocol, instead of using:
protocol Copyable
{
init(other: Self)
func copy() -> Self
}
… which causes the error, I have had to do:
protocol Copyable
{
init(other: Copyable)
func copy() -> Self
}
… but this involves having to cast the input parameter to the implementing type every time.
So, I thought I would try a generic method definition:
protocol Copyable
{
init<typeT: Copyable>(other: typeT)
func copy() -> Self
}
But, as of now, I don't seem to be able write the implementation of the init(:_) without the same need to cast from the input parameter to the implementing type thus:
required convenience init<typeT>(other: typeT)
{
self.init()
if let other = other as? Property
{
if let copyableValue = other.value as? Copyable
{
value = copyableValue.copy() as! valueT
}
else
{
value = other.value
}
}
}
What would be logical is if I could write a non-generic implementation that should satisfy the protocol's generic method definition.
Obviously, this is not yet possible in Swift but, logically, this should work:
class Property<valueT : DefaultValueProvider & Equatable> : Copyable
{
var value = valueT()
init() { }
required convenience init(other: Property)
{
self.init()
if let copyableValue = other.value as? Copyable
{
value = copyableValue.copy() as! valueT
}
else
{
value = other.value
}
}
}
I am porting my C# MVP framework to Swift and, still, I am finding it takes an awful lot of effort and ingenuity to circumvent a lack of language features that I have been used to for many years.