Movash Movash - 3 years ago 76
Swift Question

How to get some parameter in the child class through the base class

I'm stuck.
I try to make right code's architect but I can not solve following case:
I have some base class and inherited from it class like:

class BaseClass {
var name: String
init(name: String) { = name

class ChildClass: BaseClass {
var otherName: String
init(otherName: String) {
self.otherName = otherName

And the following function:

func someFunc() -> BaseClass {
let a = ChildClass.init(otherName: "NAME")
return a

How can I get the parameter "otherName"?
The available parameter is only one - "name", but I want to get "otherName":

let b = someFunc()

Answer Source

You can use:

(b as! ChildClass).otherName

Your function returns your object as BaseClass object, so you can't access any of ChildClass methods. In order to access ChildClass methods, you need to cast your object to ChildClass using as!, as we know it is a ChildClass object. After that you'll be able to access all the parameters of ChildClass.

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