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

What’s the difference between a protocol and a class in Swift?

Câu trả lời

In Swift, protocols and classes serve different purposes and have distinct characteristics. Here are the key differences between them:

Definition and Purpose

  • Class: A class is a blueprint for creating objects (instances). It defines properties and methods that the created objects will have. Classes support inheritance, allowing one class to inherit the properties and methods of another.
  • Protocol: A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols do not provide implementations; they only specify what methods or properties an adopting class or struct must implement[1][3][7].

Instantiation

  • Class: You can create instances (objects) from a class. Each instance has its own copy of the properties defined in the class.
  • Protocol: You cannot create instances from a protocol. A protocol is a type definition that specifies a set of methods and properties that conforming types must implement[1][3].

Inheritance and Conformance

  • Class: Classes support single inheritance, meaning a class can inherit from only one superclass. However, a class can conform to multiple protocols.
  • Protocol: Protocols can inherit from multiple other protocols. A class, struct, or enum can conform to multiple protocols, thereby adopting the required methods and properties from each[3][4][7].

Implementation

  • Class: A class provides concrete implementations of its methods and properties. It can also provide initializers to set up its instances.
  • Protocol: A protocol does not provide implementations of its methods and properties. However, Swift allows protocols to have default implementations of methods through protocol extensions. These default implementations can be overridden by conforming types[1][3][7].

Storage

  • Class: Classes can store data directly in their properties.
  • Protocol: Protocols cannot store data. They only define the requirements for properties and methods, but do not provide s...
middle

middle

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

middle

What is typecasting?

expert

What is the use of Hashable protocol?

expert

What are the benefits of using DispatchWorkItem in Swift?

Bình luận

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

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