What is the difference between o...
What is the difference between o...
In Swift, the open
and public
keywords are both access control modifiers, but they have distinct differences in terms of accessibility and subclassing capabilities.
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
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].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
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].Keyword | Accessibility | Overridability | Subclassing |
---|---|---|---|
open | Accessible in any module | Overridable | Allowed |
public | Accessible in any module | Not Overridable | Disallowed |
// 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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào