Objects in Swift can be converted because object-oriented involves inheritance, subclasses, parents, and so on.
There are a few rules, let's talk first.
A subclass object can be converted directly to the parent class object's
The parent class object can be conditionally converted to a subclass object, which we're talking about here.
First we create three classes of people Homan men man Boys Boy
Man Inherits Homan
Boy Inherits Homan
Well, it can be said that man is a Homan subclass.
Boy is a subclass of Homan.
Homan is the father of man.
Homan is the father of boy.
Class homan{ var name= "" init (homanname:string) { name=homanname } //Self Introduction func introduce () { println ("I ' m homan My name is \ (name)") }}
Class Man:homan { var workname= "" override Func Introduce () { println ("I ' m man my name is \ (name) my Workname is \ (workname) }}
Class Boy:homan { var schoolname= "" override Func Introduce () { println ("I ' m boy my My name is \ (name) Sch Oolname is \ (schoolname) } }
First we look at the subclass into the parent class
1, the subclass object can be converted directly to the parent class object (upward transformation, direct go) var h:homan=man (homanname: "Zhang San") h.introduce () var h1:homan=boy ( Homanname: "Pony") H1. Introduce ()
Next we talk about the subclass to the parent class
2, the parent object is converted to a subclass object as! As? A parent class object that is converted to a subclass object requires the use of as! (If the current object is a parent object, but if he is a subclass object, it can be converted back to var man1=h as! Man man1.workname= "ios development" Man1. Introduce () //If you want to convert to a subclass object, but the current object is not converted by this subclass object, a run-time error occurs: Could not cast value of type// var man2=h1 as! Man //If we need to convert the current parent class object to a subclass object but not sure if the current object is a subclass object, how do I handle it? Swift provides us with a method as? If let A = h as? man{ a.workname= "IOS test" a.introduce () }else{ println ("Non-Subclass Object") } if let A = H1 as? man{ a.workname= "IOS test" a.introduce () }else{ println ("Non-Subclass Object") }
There is also a case where the current object is not known as a subclass object that is converted to a parent class object.
3 How to tell if an object is an object of this class can use the object is class to judge //We will find that the child class object is not the parent class object returned is also true println (H is Homan) println (H was man)
println (h is boy)
Okay, basically done, there's a problem to keep talking about.
Apple Development Group: 414319235 Welcome to join the Welcome discussion question
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift Object Type Conversions