Kelin Sasha Kelin Sasha - 2 months ago 7
Swift Question

Convert a class to its superclass

First, I created some classes like this:

class superClass {
}

class class1: superClass {
var a:Int = 0
}

class class2: superClass {
var b:Int = 0
}


And I constructed an array to store them:

var myClasses:[superClass] = []


I added something to the array in this way:

let newClass = class1()
newClass.a = 1
myClasses.append(newClass)


And:

let newClass = class2()
newClass.b = 2
myClasses.append(newClass)


Now I wanna check the array like this:

for eachObject in myClasses {
// code...
}


I want to classify eachObject and figure out which class it belongs to.

If it belongs to class1, I need to print the value of eachObject.a

Is there a way to make it? Thanks~

Answer

You can simply do this

for eachObject in myClasses {

    if let obj = eachObject as?  class1 {
        // class1 type object
    } else {
       // class2  type object    
   }    
}

another way to check object type using Use the type check operator is

for eachObject in myClasses {

    if eachObject is  class1 {
        // class1 type object
    } else if eachObject is class2 {
        // class2  type object
    }
}