The opening

Class and Struct are two important data structures in Swift, and are also required questions in Swift interview questions. Therefore, a thorough understanding of classes and structs will help us learn Swift.

Understand the Class

Definition and use of Class

class Animal { var name: String? Var weight = 0.0}let cat = Animal()
cat.name = "cat"
cat.weight = 10

print("cat's name: \(cat.name!) , cat's weight: \(cat.weight)") //cat's name: cat, cat'S weight: 10.0Copy the code

Class is a reference type

When a value is passed, it is passing a reference to an existing instance. Here’s a code to explain this:

let cat = Animal()
cat.name = "cat"
cat.weight = 10

let blackCat = cat
blackCat.name = "blackCat"

print("cat's name: \(cat.name!) ") // cat's name: blackCat
Copy the code

Cat and blackCat refer to the same Animal instance. They’re just two different names for this instance. As shown below:

Note

We see that the code above declares cat and blackCat as lets, but we can still modify its properties, because the instance referenced by cat and blackCat has not changed. They still refer to the instance we just modified. Error: Cannot assign to value: ‘blackCat’ is a ‘let’ constant

Identity Operators

Swift provides === and! == to determine if two variables or constants refer to the same instance(only for class, think about why structs don’t).

if blackCat === cat {
    print("Identical") //Identical
} else {
    print("Not identical")}Copy the code

= = =and= =It’s different.

  • = = =: represents the same instance referenced by two variables or constants
  • = =: indicates whether two variables or constants have the same value, not necessarily the same instance referenced
  • If you want custom class support= =Operator to make the class conform to Equatable
class Animal { var name: String? Var weight = 0} extension Animal: Equatable {static func == (LHS: Animal, RHS: Animal) -> Bool {return lhs.name == rhs.name && lhs.weight == rhs.weight
    }
}

let cat = Animal()
cat.name = "cat"
cat.weight = 10

let blackCat = cat
blackCat.name = "catName"

let whiteCat = Animal()
whiteCat.name = "catName"WhiteCat. Weight = 10.0if blackCat === cat {
    print("Identical") //Identical
} else {
    print("Not identical")}if whiteCat === blackCat {
    print("Identical")}else {
    print("Not identical") //Not identical
}

if whiteCat == blackCat {
    print("Equal")}else {
    print("Not Equal") //Equal
}
Copy the code

Understand the Struct

Struct definition and use

Struct FPoint {var x = 0.0 var y = 0.0 var x = 0.0 var y = 0.0 Double) { self.x = self.x + add } }let p1 = FPoint()
print("p1's x : \(p1.x), p1's y: \(p1.y)") // p1X: 0.0, p1'S y: 0.0Copy the code

Struct is a value type

When a value is passed, it copies the value passed. Here’s a code to explain this:

Var p2 = p1 p2.x = 3.0print("p1's x : \(p1.x), p1's y: \(p1.y); p2's x : \(p2.x), p2's y: \(p2.y)")
//p1's x: 1.0, p1'S y: 2.0; p2's x: 3.0, p2'S y: 2.0Copy the code

As can be seen from the above code, assigning P1 to P2 and then changing the value of P2 does not affect the value of P1. This is because assigning P1 to P2 copies an instance with the same value as P1, and then assigns the copied instance to P2. As shown below:

Note

If a struct instance is declared as a let, you cannot change the instance value. Such as

letP1 = FPoint(x: 1.0, y: 2.0) p1. X = 10.0'p1' is a 'let' constant
Copy the code

How do I choose structs and classes in a project

  • The default is struct
  • Use class when you need to inherit objective-C classes
  • Use class when you need to control uniqueness
  • Use struct and Protocol to implement model inheritance and sharing behavior, as shown in the following code:
protocol AnimalCommonProtocol {
    var name: String? { get set }
    var weight: Double { get set }
    func run()
}

struct Cat : AnimalCommonProtocol {
    func run() {
        print("cat run")
    }
    var name: String?
    var weight: Double
    var gender: String?
}

struct Dog : AnimalCommonProtocol {
    func run() {
        print("dog run")
    }
    
    var name: String?
    var weight: Double
    var type: String?
}
Copy the code

To sum up: don’t use classes when you can use structs

Why is struct preferred

  • Structs do not need to worry about memory leaks and multithreaded reads and writes because they copy values as they are passed
  • Structs are stored in the stack, classes are stored in the heap, and structs are faster

conclusion

The same

  • Can define property, method, initializers
  • Both support Protocol and Extension

The difference between

  • Class is a reference type; Struct is a value type
  • Class supports inheritance; Structs do not support inheritance
  • Class declared method modification properties are not requiredmutatingKey words; Struct need
  • Class does not provide default Memberwise Initializer; Struct provides default Memberwise Initializer
  • Class supports Reference counting. Struct is not supported
  • Class supports Type casting; Struct is not supported
  • Class support Deinitializers; Struct is not supported

reference

  • Structures and Classes
  • Equivalence Operators
  • Choosing Between Structures and Classes
  • Why Choose Struct Over Class?