Swift USES the final keyword to prevent overwriting

  • 2020-05-27 07:19:21
  • OfStack

The final keyword, which exists in most programming languages, means that it is not allowed to inherit or remanipulate what it modifies. In Swift, the final keyword can be modified before class, func, and var.

It is generally accepted that final provides better versioning, better performance, and more secure code. Here's an example code to show you that swift USES the final keyword to prevent overwriting.


 /**
    with final Keywords to prevent overwriting 
   final Final, final, final ; The decisive ; unchangeable 
   final  Modifies a class to indicate that it cannot be inherited. 
    If a property or method is modified, the corresponding property or method cannot be overridden. 
   */
  class Observer {
//   final  add 
    var storeProperty: Int = 0 {
    willSet {
     print("storeProperty father will Set")
    }
    didSet {
     print("storeProperty father did Set")
    }
   }
   // final
   //  You cannot set a property viewer for a calculated property 
    var computeProperty: Int {
    get {
     return 0
    }
    set {
     print("Do nothing!")
    }
   }
   //final
   func dodododTest() -> Void {
    print("dadadadadaddadaad")
   }
  }
  class ChildOfObserver: Observer {
   //  You can override a variable store property in a parent class 
   override var storeProperty: Int {
    willSet {
     print("storeProperty will Set")
    }
    didSet {
     print("storeProperty did Set")
    }
   }
   //  You can override the property viewer for a computed property in a parent class 
   override var computeProperty: Int {
    willSet {
     print("computeProperty will Set")
    }
    didSet {
     print("computeProperty did Set")
    }
   }
   override func dodododTest() {
   }
  }
  let co = ChildOfObserver.init()
  co.storeProperty = 10

Related articles: