protocols + variables + type issue

I have a protocol, in which I define a variable.

public protocol CNEnvelopment {
    var pan : CGPoint {get set}
    var zoom : Float {get set}
    
    var dagObjs : [CNDagObj] {get set} // this one.

I use that protocol type coerce another type, to shield myself from having to test the object type, and write about 30 lines of code for the same behavior in a series of classes:

(theParent as! CNEnvelopment).dagObjs.insert(contentsOf: droppedItems, at: theIndex + 1)


but I get an error when I do that:

Cannot use mutating member on immutable value of type '[CNDagObj]'


do I need to just throw the protocol away and use a class? Because it will work properly if I make CNEnvelopment a class.

is this a limitation of protocols?

Accepted Reply

var.

if var envelope = theParent as? CNEnvelopment{ 

Replies

Please show more context.


As far as I tried, this compiles:

var theParent: CNEnvelopment = MyEnvelopment()
theParent.dagObjs.insert(contentsOf: droppedItems, at: theIndex + 1)


So, the problem is `as!`-casting. Why do you need it? How have declared `theParent`?

there is a parent class to the classes that are CNEnvelopment.


so the child classes are something like :


public class CNNode : CNDagObj, CNIdentity, CNProperties, CNEnvelopment, CNStackObj, CNDagConnection, BKObserver, CNRenderable, CNOutputsObj {

CNDagObj is the parent class. Not all CNDagObjects are CNEnvelopment.

the Property in which we find the CNEnvelopment, is of the class CNDag.

public var parent : CNDagObj? = nil

all objects that will be a parent, will also be CNEnvelopment, But as I recall... the compiler doesn't like it if I do this instead :

public var parent : CNEnvelopment? = nil

so I'm stuck with the next lowest common denominator class (CNDag)


i suppose i should :

if let envelope = theParent as? CNEnvelopment{

?

var.

if var envelope = theParent as? CNEnvelopment{