美文网首页
The Swift Programming Language--

The Swift Programming Language--

作者: ted005 | 来源:发表于2015-07-17 20:03 被阅读40次

    Type Casting

    1. Type check operator: is
    2. Type cast operator: as? or as!
    • Defining a Class Hierarchy for Type Casting
      class Person {
      var name: String
      init(name: String){
      self.name = name
      }
      }

      class Teacher: Person {
          var class: String
          init(name: String, class: String){
              self.class = class
              super.init(name)
          }
      }
      
      class Student: Person {
          var studentId: Int
          init(name: String, studentId: Int){
               self.studentId = studentId
               super.init(name)
          }
      }
      
      //campus is of type Person
      let campus = [Teacher("Ted", "Math"), Teacher("Ruth", "English"), Teacher("Paul", "Nature"), Student("Amy", 001), Student("Andy", 002)]
      
    • Checking Type
      for person in campus {
      if person is Teacher {
      print("(person.name) is a teacher.")
      }
      else if person is Student {
      print("(person.name) is a student.")
      }
      }

    • Down Casting
      1.as? return an optional value
      2.as! will trigger runtime error of cast fail
      3.switch case use as(forced cast operator), not as?

      //optional type cast
      for person in campus {
           if let teacher = person as? Teacher {
                print("\(teacher.name) is a \(teacher.class) teacher.")
           }
           else if let student = person as? Student {
                print("\(student.name)'s ID is \(student.studentId).")
           }
      }
      
       //forced type cast
       let teachers: [AnyObject] = [Teacher("Ted", "Math"), Teacher("Ruth", "English"), Teacher("Paul", "Nature")]
       
        for obj in teachers {
            let teacher = obj as! Teacher
            print("\(teacher.name) is a \(teacher.class) teacher.")
        }
      

    The cases of a switch statement use the forced version of the type cast operator (as, not as?) to check and cast to a specific type. This check is always safe within the context of a switch case statement.

    相关文章

      网友评论

          本文标题:The Swift Programming Language--

          本文链接:https://www.haomeiwen.com/subject/lakpqttx.html