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

What is the difference between o...

Câu trả lời

In Swift, the open and public keywords are both access control modifiers, but they have distinct differences in terms of accessibility and subclassing capabilities.

Accessibility

  • Open: The open keyword allows a class, struct, or protocol to be accessible from any module. This means that any code, whether it is in the same module or a different module, can access the entity marked as open[1][2][6].
  • Public: The public keyword also allows a class, struct, or protocol to be accessible from any module. However, it does not permit the same level of flexibility in terms of subclassing and overriding[1][2][6].

Overridability and Subclassing

  • Open: When a class is marked as open, it can be subclassed both within the same module and from other modules. Additionally, methods and properties marked as open can be overridden in subclasses. This makes the open keyword the most permissive access level in Swift[1][2][6].
  • Public: A class marked as public can be accessed from any module, but it cannot be subclassed outside the module it is defined in. Similarly, methods and properties marked as public cannot be overridden outside their defining module. This restriction helps to maintain a controlled inheritance hierarchy and prevents unintended modifications from external modules[1][2][6].

Summary Table

Keyword Accessibility Overridability Subclassing
open Accessible in any module Overridable Allowed
public Accessible in any module Not Overridable Disallowed

Example

// Open class example
open class Person {
    open var firstName: String?
    open var lastName: String?
    open var age: Int?
    open var address: String?
}

class Student: Person {
    var school: String?
    var grade: Int?
    var score: Double?
}

// Public class example
public class Animal {
    public var species: String?
    public var age: Int?
...
senior

senior

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

middle

What is trailing closure syntax?

middle

What's the main difference between the Array , Set and Dictionary collection
type?

expert

What’s the difference between init?() and init() ?

Bình luận

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

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