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

What are the differences between functions and methods in Swift?

Câu trả lời

In Swift, functions and methods are both reusable chunks of code that perform specific tasks, but they have distinct differences in terms of their association with types and how they are called.

Functions

  • Definition: Functions are independent pieces of code that perform a specific task. They are not associated with any particular type (class, struct, or enum).
  • Syntax: Functions are defined using the func keyword followed by the function name, parameters, and return type.
  • Calling: Functions are called by their name directly and do not require an instance of a type.
  • Scope: Functions can be defined globally, outside of any type.
  • Example:
    func sayHello() {
        print("Hello, World!")
    }
    sayHello() // Output: Hello, World!

Methods

  • Definition: Methods are functions that are associated with a specific type (class, struct, or enum). They can be either instance methods or type methods.
  • Syntax: Methods are also defined using the func keyword, but they are defined within the context of a type.
  • Calling: Methods are called on an instance of the type (for instance methods) or on the type itself (for type methods).
  • Scope: Methods must be defined within a type.
  • Instance Methods: These methods operate on instances of the type and have access to the instance's properties and other methods.
  • Type Methods: These methods are associated with the type itself and are defined using the static or class keyword.
  • Example:
    struct Car {
        var speed: Int
        
        // Instance method
        func drive() {
            print("Driving at \(speed) MPH")
        }
        
        // Type method
        static func make() -> Car {
            return Car(speed: 0)
        }
    }
    
    let myCar = Car(speed: 60)
    myCar.drive() // Output: Driving at 60 MPH
    let newCar = Car.make()

Key Differences

  • Association: Functions are not associated with any type, whereas methods are always associated with a type.
  • Calling Context: Functions are called independently, while methods are called on instances or types.
  • Access to self: Methods have access to the self keyword, which refers to the instance of the type they belong to. Functions do not have this conte...
middle

middle

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

middle

Explain the difference between DispatchQueue.main.async and DispatchQueue.main.sync ?

junior

What is the difference between Upcast and Downcast in Swift?

middle

When would you use self in a method?

Bình luận

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

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