RonnieLee RonnieLee - 3 months ago 9
Swift Question

swift pass value class parent to class child in swift

i want to pass value class parent to class child
there are two class as follow

class parent{
var aaa:String?
var bbb:String?
init(pa:String?,pb:String?){
self.aaa=pa
self.bbb=pb
}
}

class child:parent{
var ccc:String?
}


now I use like this

let p=parent(a:"1111",b:"22222")
if let c=p as? child{
print(c)
}


but all the time is nil why?
I want to get the result: c.aaa="1111" c.bbb="222" c.ccc=nil or other
and then.if i got the result like above,when i use "c" i just need give ccc a value is very convenient.but not successful .
Thank you for your help!!!

Answer

First of all let's clean up your code

class Parent {
    var a:String?
    var b:String?
    init(a:String?, b:String?) {
        self.a = a
        self.b = b
    }
}

class Child: Parent{
    var c: String?
}

Answer

With this code you create a Parent object and you put it into the parent constant.

let parent = Parent(a:"1111",b:"22222")

Then you try to cast parent as Child. But Parent is NOT a Child. So the cast will fail.

if let child = parent as? Child {
    print(child)
}

Conclusion

class Child: Parent { ...}

you are saying that a Child is also a Parent.

NOT that a Parent is a Child.

Update

If you want to create a Child object using a Parent object (if this makes sense for your business logic) here's the code

class Child: Parent{
    var c: String?

    init(parent:Parent, c:String) {
        super.init(a: parent.a, b: parent.b)
        self.c = c
    }        
}

let parent = Parent(a: "a", b: "b")
let child = Child(parent: parent, c: "c")
child.a // "a"
child.b // "b"
child.c // "c"

has-a instead of is-a

Another possible solution is avoiding subclassing, here's the code

struct Parent {
    var a:String?
    var b:String?
}

struct Child {
    var c: String?
    var parent: Parent
}

Now Child is not a Parent but contains a Parent

You probably should rename them

Now given a parent

let parent = Parent(a: "a", b: "b")

you can easily create a Child

let child = Child(c: "c", parent: parent)

And this is how you use the child

child.parent.a // "a"
child.parent.b // "b"
child.c // "c"