Câu hỏi phỏng vấn Swift
Câu hỏi

What Classes and Structs have in common in Swift and what are their differences?

Câu trả lời

In Swift, both classes and structs are fundamental building blocks used to define custom data types. They share several similarities but also have key differences that influence their use in different scenarios.

Similarities Between Classes and Structs

  1. Properties and Methods: Both classes and structs can define properties to store values and methods to provide functionality[3][6].
  2. Initializers: Both can define initializers to set up their initial state[3][6].
  3. Subscripts: Both can define subscripts to provide access to their values using subscript syntax[3].
  4. Extensions: Both can be extended to add new functionality beyond their original implementation[3][6].
  5. Protocols: Both can conform to protocols to provide standard functionality of a certain kind[3][6].

Differences Between Classes and Structs

  1. Value Type vs Reference Type:

    • Structs are value types, meaning they are copied when they are assigned to a variable or constant, or when they are passed to a function. Each instance of a struct is independent of others[1][4][5][6].
    • Classes are reference types, meaning they are passed by reference. When you assign a class instance to a variable or pass it to a function, you are working with a reference to the same instance[1][4][5][6].
  2. Inheritance:

    • Structs do not support inheritance. They cannot inherit properties or methods from another struct[1][4][5][6].
    • Classes support inheritance, allowing one class to inherit properties and methods from another class. This enables the creation of class hierarchies[1][4][5][6].
  3. Deinitializers:

    • Structs cannot have deinitializers. They are deallocated automatically when they go out of scope[4].
    • Classes can have deinitializers, which are called when an instance of the class is deallocated from memory[4].
  4. Memory Management:

    • Structs are stored on the stack, which makes them more efficient for small, simple data types. They do not use reference counting[2][15].
    • Classes are stored on the heap and use reference counting to manage memory. This can lead to issues like retain cycles if not managed properly[2][15].
  5. Thread Safety:

    • Structs are inherently safer in a multithreaded environment because they are copied when passed around, reducing the risk of race conditions[1][16].
    • Classes require explicit measures to ensure thread safety, as multiple references to the same instance can lead to race conditions and other concurrency issues[1][16].
  6. **Ob...

middle

middle

Gợi ý câu hỏi phỏng vấn

expert

Explain what is DispatchGroup?

middle

What are the differences between functions and methods in Swift?

middle

What is trailing closure syntax?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào