美文网首页
The Swift Programming Language--

The Swift Programming Language--

作者: ted005 | 来源:发表于2015-07-23 22:32 被阅读17次

    Inheritance

    • Defining a Base Class

    Swift classes do not inherit from a universal base class.

      class Vehicle {
          //stored property
          var currentSpeed = 0.0
          
          //read-only computed property
          var description: String{
                return "traveling a \(currentSpeed) miles per hour." 
          }
    
          func makeNoise(){
              //do nothing
          }
      }
    
    • Subclassing
      class Bycicle: Vehicle {
      var hasBasket = false
      }

      class Tandem: Bicycle {
        var numberOfPassengers = 0
      }
      
      let tandem = Tandem()
      tandem.hasBasket = true
      tandem.currentSpeed = 15
      tandem.numberOfPassengers = 2
      print("\(tandem.description)")
      
    • Overriding

    The override keyword also prompt the Swift compiler to check that your overriding class's superclass has a declaration that matches the one you provided.

     class Train: Vehicle {
        override func makeNoise(){
            print("Choo Choo")
        }
     }
    

    You can present an inherited read-only property as a read-write property by providng both a getter and setter in your subclass property override. You cannnot, however, present an inherited read-write property as a read-only property.

    If you provide a setter as part of a property override, you must also provide a getter for that override.

     class Car: Vehicle {
        var gear = 1;
    
        override var description: String {
    
            return super.description + "in gear \(gear)."
        }
     }
    

    You cannot add property observers to inherited constant stored properties or inherited read-only computed properties. The value of these properties cannot be set.

     class Car: Vehicle {
        var gear = 1
    
        override var description: String {
            willSet {
                //Wrong, read-only computed property
            }
        }
     }
    
    • Preventing Overrides

      final class
      final var
      final func
      final class func
      final subscript

    相关文章

      网友评论

          本文标题:The Swift Programming Language--

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