Reflection in Swift Swift

Source: Internet
Author: User

Swift's reflection mechanism is implemented based on a struct called Mirror, which has the following properties and methods inside it:

Let Children:children   //child nodes of the object. DisplayStyle:Mirror.DisplayStyle?   object's presentation style let SubjectType:Any.Type   //Object type Func superclassmirror (), Mirror?   The mirror of the object's parent class

Use the sample:

Example 1: The class name of the output entity object, the number of attributes, and the property names and property values of all properties. First define a user class:
User class Class {    var name:string = ""  //Name    var nickname:string?  Nickname    var age:int?   Age    var emails:[string]?  Mail address}

It then creates a user object and obtains information about the object through reflection:

Create a user instance object let User1 = User () user1.name = "Hangge" user1.age = 100user1.emails = ["[Email protected]", "[email protected ] "]         //reflect the user object let Hmirror = Mirror (reflecting:user1)         print (" Object type: \ (hmirror.subjecttype) ") Print (" The number of child elements of the object: \ (HMirror.children.count) ")         print ("---the property names and property values of the child elements of the object as follows---") for case let (label?, value) in Hmirror.children {    Print ("Property: \ (Label)     value: \ (Value)")}
The console output information is as follows: Original: http://www.hangge.com/blog/cache/detail_976.html

Reflection in Swift Swift

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.