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

What's the difference between Self vs self ?

Câu trả lời

In Swift, the terms Self and self have distinct meanings and uses, which are crucial to understand for effective programming in the language.

self

  • Definition: self refers to the current instance of a class, struct, or enum.
  • Usage: It is used to access and manipulate the instance properties, methods, and subscripts of the current object.
  • Example:
    swift Copy
    class Person {
        var name: String
        init(name: String) {
            self.name = name // 'self' is used to distinguish the instance property from the initializer parameter
        }
    }
  • Purpose: It helps avoid naming conflicts with local variables or parameters and ensures that you are working with the properties and methods of the current instance[1][2][3][5].

Self

  • Definition: Self refers to the type of the current instance. It is often used in protocols and class hierarchies to ensure type integrity.
  • Usage:
    • In Protocols: Self is used to refer to the type that conforms to the protocol, allowing for polymorphic behavior.
    • In Class/Static Methods: It can be used as the return type to indicate that the return type is the type of the class to which the method was sent, rather than the class in which the method is declared.
  • Example:
    swift Copy
    protocol Duplicatable {
        func duplicate() -> Self
    }
    
    class Document: ...
middle

middle

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

senior

What is the autoclosure attribute and when to use it?

middle

How to sort array of custom objects by property value in Swift?

senior

What's wrong with this code?

Bình luận

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

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