[置顶] 类型 & 属性

类型

第一种分类:

  • 命名型类型
    -定义时可以给定名字的类型。命名型类型包括class、Structure、Enumeration、Delegate,还包括那些表示数组、字典和可选值的类型、以及基础数据型类型(Basic Data types)
  • 复合型类型
    -没有名字的类型,它由 Swift 本身定义。函数类型和元组类型。

第二种分类:

  • Value Type(值类型)
    -如Structure、Enumeration、Tuple、Basic Data Type(integers, floating-point numbers, Booleans, strings, arrays and dictionaries)
  • Reference Type(引用类型)
    -如Class、Closure

属性

  1. 全局变量

    Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.
    Local constants and variables are never computed lazily.

  2. 类型属性(type property)

    • 用static来定义类型属性
    • 如果允许子类重写父类对计算类型属性的实现, 可以用class关键字来为类定义计算类型属性。

    ⚠️Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

    Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.

  3. 实例属性

    • 存储属性
    • 计算属性

    ⚠️You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

    -属性观察器(property observer)

    除了懒惰存储属性,你可以为任何存储属性加上属性观察者定义。另外,通过重写子类属性,也可以给继承属性(存储或计算)加上属性观察者定义。

    The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.

    • 惰性属性

    A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

    ⚠️You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

你可能感兴趣的:(type,swift,property)