As, as! And the as? Three types of conversion operators are confused. The usage of the three operators is summarized here.

  1. as

    1) Cast from derived class to base class (upcasts)

Class Person {var name: String init(_ name: String){self.name = name}} class Person {var name: String init(_ name: String){self.name = name}} Class Teacher: Person {} func showPersonName(_ people: Person){let name = people.name print(" this name is: \(name)")} // Define a Student object. Teacher_zhang var teacher_zhang = Student("teacher_zhang"); Let person1 = xiaoli as Person let person2 = teacher_zhang as Person // ShowPersonName (person1) showPersonName(person2) ------------------------ The name of Xiaoli is teacher_ZhangCopy the code

2) Eliminate ambiguity, numeric type conversion

let age = 28 as Int
let money = 20 as CGFloat
let cost = (50 / 2) as Double
Copy the code

3) Pattern matching in the switch statement detects the type of the object through the switch syntax and processes according to the type of the object.

Switch PE {case let PE as Student: print(" Case let PE as Teacher: print(" print Teacher's payroll...") ) default: break }Copy the code
  1. as! Used on Downcasting. The runtime runtime error is reported if the cast fails.

  2. as? as? And the as! The conversion rules for the operators are exactly the same. But the as? It returns a nil object if the conversion is unsuccessful. Returns the value of the optional type on success. Due to the as? There are no errors when the conversion fails, so use as! For conversions that are 100% guaranteed to succeed. Otherwise, use as?

    let person : Person = Teacher("zhanglaoshi") if let someone = person as? Teacher{print(" this person is a Teacher, name is \(someone. Name)")} else {print(" this person is not a Teacher, the value of 'someone' is nil")}Copy the code