iugo / candev

Can development be self-taught? 开发能自学吗?
The Unlicense
0 stars 0 forks source link

Swift 中 class 和 struct 有什么区别? #5

Open iugo opened 1 year ago

iugo commented 1 year ago

官方详细文档在: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/

其中, 最重要的是一句话是:

因为 class 更复杂, 所以优先使用 struct.

如果还有疑问, 参见另一份官方文档: https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes

struct 有哪些功能

  1. 可以储存属性的值.
  2. 可以有方法.
  3. 可以通过 self 对值和方法进行方法.
  4. 可以有初始化方法来初始化属性的值.
  5. 虽然不支持继承, 但支持 extension.
  6. 可以实现 protocol.

除了继承, 基本上 struct 实现了所有 class 的常见功能.