Some interview questions about swift

swift interview questions.png

1. The difference between open and public

  • public : It can be accessed by anyone else, but cannot be copied and inherited by other modules.
  • open : Can be accessed by anyone, can be inherited and copied.

Second, the difference between struct and class

  • struct is a value type and class is a reference type .
    • Variables of value types directly contain their data, and value types have their own copy of the data, so operations on one variable cannot affect another variable.
    • Variables of reference type store data references to them, so the latter are called objects, so operations on one variable may affect the object referenced by another variable.
    • The essential difference between the two: struct is a deep copy, copying the content; class is a shallow copy, copying the pointer .
  • The initialization of the property is different : the class cannot directly put the property in the parameter of the default constructor during initialization, but needs to create a constructor with parameters by itself; while the struct can put the property in the parameter of the default constructor.
  • Variable assignment methods are different : struct is a value copy; class is a reference copy.
  • Immutable variable : The variable content and immutable content of swift are distinguished by var and let. If the initial variable of let is modified, a compilation error will occur. Struct follows this characteristic; class does not have such a problem .
  • Mutating function : The difference between struct and class is that the function of struct needs to add mutating when changing the value of property, while class does not.
  • Inheritance : struct cannot be inherited, class can be inherited.
  • Struct is lighter than class: struct is allocated on the stack, and class is allocated on the heap.

3. Swift uses struct as a data model

3.1 Advantages

  1. Security : Because Structs are passed by value, they are not reference counted.
  2. Memory : Since they have no reference count, they will not cause memory leaks due to circular references.
  3. Speed : Value types are typically allocated on the stack, not the heap. So they are much faster than Class!
  4. Copy : To copy an object in Objective-C, you must choose the correct copy type (deep copy, shallow copy), and value type copy is very easy!
  5. Thread Safety : Value types are automatically thread safe. No matter which thread you access your Struct from, it's very simple.

3.2 Disadvantages

  1. Mixed development of Objective-C and swift : the swift code called by OC must inherit from NSObject.
  2. Inheritance : structs cannot inherit from each other.
  3. NSUserDefaults : Struct cannot be serialized into NSData objects.

reference article

Talking about Struct and Class in Swift

Guess you like

Origin blog.csdn.net/u010389309/article/details/100330701