Use Common Variable for Multiple Datatypes

I have many optional variables which are subclasses of the same class:


var variable1: Experience.subclass1!
var variable2: Experience.subclass2!
var variable3: Experience.subclass3!
...


I want to use a common variable which can copy the value from any of these optional variables for easy code writing. Example:


var commonVariable = variable1
...
commonVariable = variable2 // change the value inside another function


Any ideas on how to enable this functionality? This will greatly simplify my code.

A variable is not a subclass.

Did you define SubClass1 as subclass of Experience ?

Please show the complete classes declarations, that will be easier.


If classes are nested, you can do casting:


class Experience  {
    var name : String = ""
    var level : Int = 0
   
    init(name: String) {
        self.name = name
    }
}

class SubClass1: Experience {
    var value1 : Int = 1
}

class SubClass2: SubClass1 {
    var value2 : Int = 2
}

var variable1 = SubClass1(name: "var1")
var variable2 = SubClass2(name: "var2")
print(variable2.name, variable2.value2)
var variable = variable1
print(variable.name, variable.value1)

variable = variable2 as SubClass1
print(variable.name, variable.value1)


gives

var2 2

var1 1

var2 1

I have many optional variables which are subclasses of the same class:

What is the same class? How subclasses are defined? Please show enough code.


An example:

Assuming your subclasses are declared as...

enum Experience {
    class TheSameClass {
        //...
    }
    
    class Subclass1: TheSameClass {
        //...
    }
    
    class Subclass2: TheSameClass {
        //...
    }
    
    class Subclass3: TheSameClass {
        //...
    }
}


You just need to declare the `commonVariable` as the same class, common ancestor class of all your subclasses

var variable1: Experience.Subclass1!
var variable2: Experience.Subclass2!
var variable3: Experience.Subclass3!
//...
var commonVariable: Experience.TheSameClass = variable1
//...
commonVariable = variable2


You may use protocol in some cases similar to this, but it is not needed in this case.

Use Common Variable for Multiple Datatypes
 
 
Q