Swift type checking and conversion

Source: Internet
Author: User

inheritance occurs in subclasses and parent classes, which are the inheritance relationship class diagram for a series of classes, the person is the root class in the class hierarchy, and student is the immediate subclass of person, and the worker is the direct subclass of person.
The specific implementation code for this inheritance relationship class diagram is as follows:
Class Person {    var name:string    var age:int        func description (), String {        return "\ (name) age is: \ (AG e) "    }    Convenience init () {        self.init (name:" Tony ")        self.age =    convenience init (name: String) {        self.init (name:name, age:18)    }    init (name:string, age:int) {        self.name = name        sel F.age  = Age    }}class Student:person {    var school:string    init (name:string, Age:int, school:st Ring) {        Self.school = school        super.init (Name:name, age:age)    }}class Worker:person {    var factory  : String    Init (name:string, Age:int, factory:string) {        self.factory = Factory        super.init (Name:name, age:age)    }}



We will take this as an example to describe the type checking and conversion of swift classes, including the IS operator, as operator, and any and anyobject types.
First, using the IS operator
The IS operator can determine whether an instance is a type of a class. If the instance is a target type, the result returns True, otherwise false.
Let's look at an example:
Let Student1 = Student (name: "Tom", Age:18, School: "Tsinghua University") ①let Student2 = Student (name: "Ben", Age:28, School: "North  Beijing University ") Let Student3 = Student (name:" Tony ", age:38, School:" University of Hong Kong ") ②let Worker1 = Worker (name:" Tom ", Age:18, Factory  : "Steel mill") ③let Worker2 = Worker (name: "Ben", Age:20, Factory: "Power plant") ④let people = [Student1, Student2, Student3, Worker1, Worker2]⑤var Studentcount = 0var Workercount = 0for item in people {⑥    if Item is Worker {⑦        ++workercount    } el Se If Item is Student {⑧        ++studentcount    }}println ("Number of workers: \ (Workercount), number of students: \ (studentcount). ")


The preceding code, line ① and line ②, creates 3 student instances, and the first ③ and ④ rows Create two worker instances and then put the 5 instances into the People array collection.
In the ⑥ line, use for in to iterate through the People array collection. In the loop body, line ⑦ item is a worker expression that determines whether an element in the collection is an instance of the worker class. Similarly, the ⑧ item is an student expression that determines whether an element in the collection is an instance of the student class.
The output results are as follows:
Number of workers: 2, Number of students: 3.
Second, using the as operator
Before we introduce the as operator, let's look at the type conversions of objects, not all of which can be converted to each other. Let's look at the following statement:
Let P1:person = Student (name: "Tom", Age:20, School: "Tsinghua University")
Let P2:person = Worker (name: "Tom", Age:18, Factory: "Steel mills")
Let P3:person = person (name: "Tom", age:28)
We created 3 instances P1, P2, p3, and the types are person. P1 is an student instance, P2 is a worker instance, and P3 is a person instance. First, object type conversions must occur under inheritance, P1 and P2 are declared as person types, and instances are instantiated by the person subtype.
Instance: Person
As the writer of this program, we know that P1 is essentially a student instance, but on the surface it is the person type, and the compiler cannot infer whether the instance of P1 is person, student, or worker. We can use the IS operator to determine what kind of instance it is. It can then be converted to a subclass type using the AS operator, which converts the P1 of the person type to the student subclass type, which is referred to as a downward transformation. This conversion is risky, and if P1 is not the target type, the conversion will fail. In order to not have an exception, we can use as to convert it to an optional type of the target type, be successful, or return nil if unsuccessful.
As can be seen from table 15-1, p1 to student type conversions are down-conversion, successful, p1-to-worker type conversions are down-conversion but fail, and P1 to person type conversions do not require a downward transformation to be able to assign values successfully because P1 itself is the person type. P2 is similar to P1.
P3 differs greatly from P1 and P2, because P3 is essentially a person instance and cannot be transformed downward.
Let's look at an example:
Let Student1 = Student (name: "Tom", Age:18, School: "Tsinghua University") ①let Student2 = Student (name: "Ben", Age:28, School: "North  Beijing University ") Let Student3 = Student (name:" Tony ", age:38, School:" University of Hong Kong ") ②let Worker1 = Worker (name:" Tom ", Age:18, Factory  : "Steel mill") ③let Worker2 = Worker (name: "Ben", Age:20, Factory: "Power plant") ④let people = [Student1, Student2, Student3, Worker1, Worker2]⑤for item in people {⑥        if let Student = Item as? Student {⑦        println ("Student School: \ (Student.school)") ⑧    } else if let Worker = Item as? Worker {⑨        println ("Worker factory: \ (worker.factory)") ⑩    }    }


The preceding code, line ① and line ②, creates 3 student instances, and the first ③ and ④ lines create two worker instances. The 5 instances are then put into the people array collection.
In the ⑥ line, use for in to iterate through the People array collection. In the loop body, the first ⑦ line let Student = Item as? The student statement uses the AS operator to convert the element to the student type. If the conversion succeeds, the element is assigned to the student variable, otherwise nil is assigned to the student variable, and the conversion executes the ⑧ line code successfully. The ⑨ line code is similar to the ⑦ line code and will not be mentioned again.
The final output results are as follows:
Student School: Tsinghua University
Student School: Peking University
Student School: University of Hong Kong
Worker Factory: Steel mills
Worker Factory: Power Plant
Iii. use of any and anyobject types
Two types of indeterminate types are also available in Swift: Anyobject and any. Anyobject can represent instances of any class, and any can represent any type, including classes and other data types, as well as the basic data types of int and double.
The following example of the previous section is modified as follows:
Let Student1 = Student (name: "Tom", Age:18, School: "Tsinghua University") Let Student2 = Student (name: "Ben", Age:28, School: "Beijing  University ") Let Student3 = Student (name:" Tony ", age:38, School:" University of Hong Kong ") Let Worker1 = Worker (name:" Tom ", Age:18, Factory: "Steel mill") Let Worker2 = Worker (name: "Ben", Age:20, Factory: "Power plant") let people1: [person] = [Student1, Student2, Student3, W Orker1, Worker2]①let people2: [Anyobject] = [Student1, Student2, Student3, Worker1, Worker2]②let people3: [Any] = [stude NT1, Student2, Student3, Worker1, worker2]③for item in People3 {④        if let Student = Item as? Student {        println ("Student School: \ (Student.school)")    } else if let Worker = Item as? Worker {        println ("Worker factory: \ (worker.factory)")    }    }


The preceding code, ①, puts 5 instances into the person array, the ② line of code is to put 5 instances into the Anyobject array, and the ③ line of code is to put 5 instances into the any array.

These 3 types of arrays can be successfully placed into 5 instances, and can be traversed using the for Int loop in line ④, and other type codes are no longer explained.


For more information, please pay attention to the first swift book "Swift Development Guide" book Exchange discussion website: http://www.51work6.com/swift.phpWelcome to the SWIFT Technical discussion group: 362298485

Welcome to Luxgen iOS Classroom public Platform



Swift type checking and conversion

Related Article

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.