Nicolas Peslerbe Nicolas Peslerbe - 1 year ago 80
Swift Question

Variable 'xxx' was never mutated; in derived class

I'm posting my first message here, I've a logical question about swift language. For your information, I'm quite new in swift language, I'm use to code in c++ and it's a bit hard for me to have an objective point of view on how to do things right (in an elegant way), if you have some advices, pls feel free to do your suggestions.

I'm doing a homemade encapsulation using the following superclass :

class MultiLevel_encapsulation {

var separator = "";

var datas:[String:String] = [:]

func wrap() -> String{
var out:String = ""
var i = 0
for (key, data) in datas{
if i==0{
out += key + separator + data
}
else{
out += separator + key + separator + data
}

i+=1
}
return out
}

func unwrap(content:String){
let split = content.components(separatedBy: separator)
var i = 1
while(i < split.count){
datas[split[i-1]] = split[i]
i += 2
}
}

func getAttributesNames() -> [String]{
var out:[String] = []
for (key, _) in datas{
out.append(key)
}
return out
}


func getValue(name:String) -> String? {
return datas[name];
}

func setValue(name:String, value:String){
datas[name] = value;
}

}


and I want to create some subclasses including the superclass, I just change the separator depending of the subclass name :

class Level5_encapsulation: MultiLevel_encapsulation{
init(message:String) {
super.init()
separator = "&&LEVEL5&&"
unwrap(content:message)
}
override init() {
super.init()
separator = "&&LEVEL5&&"
}

}


So after it I just need to create the subclass as a var in my program, add values and wrap it to have an encapsulated string :

var l5message = Level5_encapsulation()
l5message.setValue(name: #anyTitle#, value: #anyValue#)
var output = l5message.wrap() // String with encapsulated message


Do you think it 's the right way to do it or is there a better way for that ?

My main question is about this compiler warning :

Variable 'l5message' was never mutated; consider changing to 'let' constant


I changed it for a let and it works.

So there is something I don't understand : Why can I change proprieties in the superclass as if the inherited subclass is declared as constant ? Where is the storage of the superclass and how does it works ?

Answer Source

In Swift classes and structs behave a bit differently than in C++. var and let prevent changes to the actual value, and since the variable type that you're using is a class the variable holds a reference, and not the actual data (Like Level5_encapsulation *l5message).

Since you're not mutating the value of the variable (A reference), the compiler raises a warning.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download