Swift中 struct 和 class 的区别

96
派大星的博客
2018.09.01 22:45* 字数 384

类和结构体的相同点:

a、属性
b、方法
c、下标操作
d、构造器
e、扩展
f、协议


Structures and classes in Swift have many things in common. Both can:

  • Define properties to store values
  • Define methods to provide functionality
  • Define subscripts to provide access to their values using subscript syntax
  • Define initializers to set up their initial state
  • Be extended to expand their functionality beyond a default implementation
  • Conform to protocols to provide standard functionality of a certain kind

类和结构体的不同点:

a、类具有:继承、析构、类型转换、引用计数
b、类和结构体在内存中的实现机制的不同:类存储在堆(heap)中,结构体存储在栈(stack)中
c、类是引用类型,而结构体是值类型


Classes have additional capabilities that structures don’t have:

  • Inheritance enables one class to inherit the characteristics of another.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • Deinitializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.

如何选择:

a、默认情况下使用structures。
b、当您需要Objective-C互操作性时,请使用classes。
c 、当您需要控制建模数据的标识时,请使用classes。
d 、通过共享实现,使用structures和协议来采用行为。

Consider the following recommendations to help choose which option makes sense when adding a new data type to your app.

  • Use structures by default.
  • Use classes when you need Objective-C interoperability.
  • Use classes when you need to control the identity of the data you're modeling.
  • Use structures along with protocols to adopt behavior by sharing implementations.
struct Student {
    //  MARK: - 属性
    var name: String
    var age: Int
    var classNum: String
    
    //  MARK: - 方法
    func descriptionStudent() {
        print("姓名:" + name + " 年龄:" + "\(age)" + " 班级号:" + classNum)
        // self.name = "alice"
    }
    
    mutating func modifyName(name: String){
        self.name = name
    }
}

var student1 = Student(name: "andy", age: 15, classNum: "0501")
student1.descriptionStudent()

// 输出:
// 姓名:Andy 年龄:15 班级号:0501
// 姓名:Bob 年龄:15 班级号:0501
IOS 开发日记
Gupao