5.14 Application of parent class in instance type conversion [Swift original tutorial]

Original: http://coolketang.com/staticCoding/5a9925adac502e5d51cb4e8c.html

1. This lesson will explain to you, the application of the parent class when converting the type of the instance. 



2. First define a class called Creature. 


3. Then add a name attribute to the class. 


4. Through the initialization method, set the value of the name property. 


5. Next, create a class called Dog and inherit from the Creature class. 


6. Then add a host property to the class. 


7. Add an initialization method. 


8. Set the value of the host attribute in turn, and call the initialization method of the parent class to set the value of the name attribute. 


9. Create an array of creature types as the parent class. 


10. Add instance objects of the three subclasses to the array and set their name and owner properties respectively. 


11. Then through the loop statement, traverse the elements in the array. 


12. Cast the elements to be traversed by converting the identifiers, casting their types from the superclass to the subclass's type. In this way, the value of each attribute of the element can be obtained and output. 


13. Use another loop statement and cast the array to the type of the subclass. Finally, click the display debug area icon at the bottom to observe all the logs output through the console. 


14. 


This article is organized from: "Swift4 Interactive Tutorial", the real [Hands-on] teaching mode, get started with iOS development and Swift language at the fastest speed, free download from Apple Store App Store: https://itunes.apple.com/cn/app/id1320746678 , or scan the QR code at the bottom of this page . Course supporting material download address: data download


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325380404&siteId=291194637