swift - Inherit from class with private initializer? -
consider following class hierarchy in swift:
gmsmarker class provided googlemaps library. has 2 public initializers (one designated, 1 convenience).
mapitem, clusteritem , cluster part of model. don't want allow construction of mapitem objects; clusteritems , clusters. since swift doesn't have abstract classes, having private initializer sufficient purposes. however, given mapitem inherits gmsmarker convenience constructor, can't override designated initializer private.
given rules of initializer inheritance in swift, way i've been able prevent construction of mapitem class declaring new private initializer different signature base class initializers aren't inherited.
class mapitem : gmsmarker { private init(dummyparam: int) { super.init() } }
so far good. now, when trying create initializer clusteritem class, run problem.
class clusteritem : mapitem { weak var post: post? init(post: post) { self.post = post super.init(dummyparam: 0) } }
i receive following compiler error on line calls super.init(): 'mapitem' not have member named 'init'
.
if omit call super.init, receive following error: super.init isn't called before returning initializer
.
is there way of accomplishing want in swift. keep inheritance hierarchy if possible because mapitem contains common implementation code clusteritem , cluster. furthermore, able reference both clusteritems , clusters using collection of mapitems.
there various ways solve issue:
declare initializer
internal
, give module access , subclass able call it.declare classes in same file,
private
won't issue anymore (private
enables access same file).instead of abstract classes, can make
mapitem
protocol
,clusteritem
,cluster
inheritgmsmarker
directly. however, solution may not depending on exact needs.
Comments
Post a Comment