[swift-users] Static type when expecting dynamic type
Howard Lovatt
howard.lovatt at gmail.com
Wed Feb 1 22:49:13 CST 2017
Hi All,
Anyone know what is going on here:
//: Closure picks up static type not dynamic
class MutableReference<T> {
init() {
guard type(of: self) != MutableReference.self else {
fatalError("MutableReference is an abstract class; create a
derrivative of MutableReference")
}
}
var value: T {
get {
fatalError("Calculated property value getter should be
overridden")
}
set {
fatalError("Calculated property value setter should be
overridden")
}
}
}
class DefaultMutableReference<T>: MutableReference<T> {
private var _value: T
override var value: T {
get {
return _value
}
set {
_value = newValue
}
}
init(_ value: T) {
_value = value
}
}
let e: (MutableReference<[Int]>, Int) -> Void = { $0.value.append($1) }
let dmr = DefaultMutableReference([2])
dmr.value // [2]
e(dmr, 2) // fatal error: Calculated property value getter should be
overridden
dmr.value // Expect [2, 2]
If I change `e` to:
let e: (DefaultMutableReference<[Int]>, Int) -> Void = {
$0.value.append($1) }
It works fine.
IE the closure is using the static type of its first argument and not
dynamically dispatching.
Am I doing something wrong? Is there a way round where I can still use the
base class for `e`?
Thanks for any help in advance,
-- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170202/e823969e/attachment.html>
More information about the swift-users
mailing list