Type Casting in swift with example

Using a broad type allows us to keep our code modular and manageable. It allows us to extend functionality at will. But at times we need to go specific to use the functionality specific to a particular type. In swift, we use inheritance and protocol as broad types as shown below

protocol Alphabet {
func ascii() -> Int
}

class A : Alphabet {
  let ascii = 66
  let specificToAProperty = "first alphabet"
  func ascii()-> Int {
   return self.ascii
  }
}

class B : Alphabet {
  let ascii = 66
  let specificToBProperty = "second alphabet"

  func ascii()-> Int {
   return self.ascii
  }
}

class C : Alphabet {
  let ascii = 67
  let specificToCProperty = "third alphabet"
  func ascii()-> Int {
   return self.ascii
  }
}
....

As you can see in the example above that we have created classes that conform to the protocol Alphabet. And as we all know that we can create an Array to store instances of classes A, B, and C.

var alphabetArray:[Alphabet] = [Alphabet]()
let a = A()
let b = B()
let c = C()

alphabetArray.append(a)
alphabetArray.append(b)
alphabetArray.append(c)

Now we have an array that contains instances of A, B, C which seems heterogeneous but since each one conforms to Aphabet protocol it’s ok. Now let’s see an example of using them as broad Alphabet type and then as individual-specific type

for i in alphabet {
//print ascii code using broad Alphabet type
   print("\(i.ascii())")

//print properties specific to each instance using type casting
   if a = i as? A {
     print(a.specificToAProperty)
   }

   if b = i as? B {
     print(a.specificToBProperty)
   } 

   if c = i as? C {
     print(a.specificToCProperty)
   }  
}

As you can see the ascii() function is available without typecasting but if want to access property specific to an instance type we need to use typecasting.

NEED A JOB? NEED TO HIRE? NEED HELP?

Join group of Software Professionals

iOS DEVELOPER’S DEN