Swift 零碎知识

关于继承

SwiftUI 的解决方案

struct没有继承的功能,所以SwiftUI里面也不能像UIKit那样做写一个BaseView,然后子类继承里面的所有功能。网上有大神给出了这一点的解决方案 Creating BaseView class in SwiftUI

重写

  1. 子类重写父类的属性后,也能通过super.someProperty获取父类的属性

关于类初始化

  1. 通过给存储属性赋默认值,或者在初始化函数(包括便利构造器)中给存储属性赋值,不会触发该变量的didSet
  2. 初始化构造器的三条法则:
  • A designated initializer must call a designated initializer from its immediate superclass.
  • A convenience initializer must call another initializer from the same class.
  • A convenience initializer must ultimately call a designated initializer.
initializerDelegation01_2x
  1. 构造器自动继承法则:
  • If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
  • If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.
参考:https://docs.swift.org/swift-book/LanguageGuide/Initialization.html