Swift type check and conversion, Swift type check Conversion

Source: Internet
Author: User

Swift type check and conversion, Swift type check Conversion
Inheritance occurs in subclass and parent class. It is a series of class inheritance relationship class diagrams. Person is the root class in the class hierarchy, and Student is the direct subclass of Person, worker is the direct subclass of Person.
The specific implementation code of this inherited link class diagram is as follows:

Class Person {var name: String var age: Int func description ()-> String {return "\ (name) age: \ (age)"} convenience init () {self. init (name: "Tony") self. age = 18} convenience init (name: String) {self. init (name: name, age: 18)} init (name: String, age: Int) {self. name = name self. age = age} class Student: Person {var school: String init (name: String, age: Int, school: String) {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 )}}



Next we will take this as an example to introduce the Swift class type check and conversion, including the is operator, as operator, and Any And AnyObject types.
I. Use the is Operator
The is operator can determine whether an instance is of a class type. If the instance is of the target type, true is returned; otherwise, false is returned.
The following is an example:
Let Student1 = Student (name: "Tom", age: 18, school: "Tsinghua University") ① let Student2 = Student (name: "Ben", age: 28, school: "Peking University") let Student3 = Student (name: "Tony", age: 38, school: "Hong Kong University") ② let Worker1 = Worker (name: "Tom ", age: 18, factory: "steel mills") ③ let Worker2 = Worker (name: "Ben", age: 20, factory: "Power Plant") ④ let people = [Student1, student2, Student3, Worker1, Worker2] ⑤ var StudentCount = 0var W OrkerCount = 0for item in people {6 if item is Worker {7 ++ WorkerCount} else if item is Student {Worker ++ StudentCount} println ("Worker count: \ (WorkerCount), number of students: \ (StudentCount ). ")


The above Code creates three Student instances, row ③ and row ④ creates two Worker instances, then, add the five instances to the people array set.
Use for in to traverse the people array set in Row 6. In the loop body, the item is Worker expression in line 7 is used to determine whether the elements in the set are instances of the Worker class. Similarly, the item is Student expression in the nth row is used to determine whether the element in the set is an instance of the Student class.
The output result is as follows:
Number of workers: 2; Number of students: 3.
Ii. Use the as operator
Before introducing the as operator, let's take a look at object type conversion. Not all types can be converted to each other. See the following statement first:
Let p1: Person = Student (name: "Tom", age: 20, school: "Tsinghua University ")
Let p2: Person = Worker (name: "Tom", age: 18, factory: "steel mill ")
Let p3: Person = Person (name: "Tom", age: 28)
We have created three instances p1, p2, and p3, all of which belong to the Person type. P1 is a Student instance, p2 is a Worker instance, and p3 is a Person instance. First, object type conversion must take place under the premise of inheritance, p1 and p2 are declared as the Person type, and the instance is instantiated by the Person subtype.
Instance: Person
As the creator of this program, we know that p1 is essentially a Student instance, but on the surface it is a Person type, and the compiler cannot infer whether the p1 instance is Person, Student, or Worker. We can use the is operator to determine which type of instances it is. Then, you can use the as operator to convert the type of Person to the subclass type, that is, to convert the p1 type of Person to the Student subclass type. This type of conversion is called downward transformation. This conversion is risky. If p1 is not the target type, the conversion will fail. To avoid exceptions, we can use? Convert it to an optional type of the target type. If it succeeds, it is converted. If it fails, nil is returned.
As can be seen from the 15-1 table, the type conversion from p1 to Student is downward transformation and can be successful. The type conversion from p1 to Worker is downward transformation but will fail, the type conversion from p1 to Person can be successfully assigned a value without the need for downward transformation, 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.
The following is an example:
Let Student1 = Student (name: "Tom", age: 18, school: "Tsinghua University") ① let Student2 = Student (name: "Ben", age: 28, school: "Peking University") let Student3 = Student (name: "Tony", age: 38, school: "Hong Kong University") ② let Worker1 = Worker (name: "Tom ", age: 18, factory: "steel mills") ③ let Worker2 = Worker (name: "Ben", age: 20, factory: "Power Plant") ④ let people = [Student1, student2, Student3, Worker1, Worker2] ⑤ for item in people {6 if Let Student = item? Student {7println ("Student school: \ (Student. school)") Student} else if let Worker = item? Worker {Worker println ("Worker factory: \ (Worker. factory)") Worker }}


The above Code creates three Student instances, row ③ and row ④ creates two Worker instances. Then, add the five instances to the people array set.
Use for in to traverse the people array set in Row 6. In the loop body, let Student = item? Student statement using? The operator converts an element to the Student type. If the conversion is successful, assign the element to the Student variable. Otherwise, assign the nil value to the Student variable. The conversion is successful and the code in the nth line is executed. The first line of code is similar to the seventh line of code.
The output result is as follows:
Student school: Tsinghua University
Student school: Peking University
Student school: Hong Kong University
Worker factory: steel mills
Worker factory: Power Plant
Iii. Any and AnyObject types
In Swift, two types are provided to indicate the uncertain types: 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 basic data types of Int and Double.
The example in 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: "Peking University") let Student3 = Student (name: "Tony", age: 38, school: "Hong Kong University") 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, Worker1, Worker2] ① let people2: [Any Object] = [Student1, Student2, Student3, Worker1, Worker2] ② let people3: [Any] = [Student1, Student2, Student3, Worker1, worker2] ③ for item in people3 {④ if let Student = item? Student {println ("Student school: \ (Student. school)")} else if let Worker = item? Worker {println ("Worker factory: \ (Worker. factory )")}}


Line ① Of the above Code is to put the five instances into the Person array, and line ② code is to put the five instances into the AnyObject array, the Code in line ③ puts the five instances into the Any array.

These three types of arrays can be successfully put into five instances, and can be traversed in the forth row using the for Int loop, other types of code will not be explained.


For more information, please refer to the first domestic Swift book "Swift development guide" for discussion. Website: http://www.51work6.com/swift.phpwelcome to the swifttechnology discussion group: 362298.pdf

Welcome to Zhijie iOS public classroom Platform




Where does java object type information exist? What checks are required for forced type conversion to ensure program correctness?

JVM maintains a memory area called the method area. The method area stores the type information used, such as the fully qualified name of the Class, the fully qualified name of the parent Class, the pointer to the classloader, And the pointer to the Class object.

All objects created on the stack have a pointer back to the Method Area, which points to the actual type information of the object.

When instanceof is executed, JVM obtains the result by searching the type information in the method area. During type conversion, JVM also needs to check the type information to determine whether the conversion is valid.

Type conversion in java

Java data type is strongly typed, meaning that each variable or constant must have a clear data type (for example, the basic type of int char byte .. or other custom types)
Therefore, the java compiler checks every variable or constant during compilation, and only some operations can be performed for the same data type.
For example
// I is an integer
Int I = 0;
// C is char type
Char c = '1 ';
When I and c are added, an exception is thrown.
Therefore, you must first convert the type of c to the int type (method: int (c ))
However, if c = 'X' (which is not a number in it), it cannot be converted.
The above is the most basic, and other learning will be further understood.
For specific types of conversion methods, you can find many types of conversion in java.

Hope the above can help you understand

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.