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

What’s the difference bet...

Câu trả lời

In Swift, the difference between init?() and init() lies in their behavior when initialization fails. Here’s a detailed explanation:

init()

  • Purpose: A regular initializer that ensures all properties of an instance are set to valid values before the instance is used.
  • Behavior: It always creates a fully initialized instance of the class, struct, or enum.
  • Syntax:
    swift Copy
    init() {
        // Initialization code
    }
  • Example:
    swift Copy
    struct Person {
        var name: String
        init(name: String) {
            self.name = name
        }
    }
    let person = Person(name: "John")

init?()

  • Purpose: A failable initializer that can return nil if the initialization fails due to invalid parameters or other conditions.
  • Behavior: It returns an optional instance (nil if initialization fails).
  • Syntax:
    swift Copy
    init?(parameter: Type) {
        guard condition else {
            return nil
        }
        // Initialization code
    }
  • Example:
    swift Copy
    struct Person {
        var name: String
        init?(name: String) {
            guard !name.isEmpty else {
                return nil
            }
            self.name = name
        }
    }
    if let person = Person(name: "John") {
        print("Person created: \(person.name)")
    } else {
        print("Failed to create person")
    }

Key Differences

  1. Return Type:

    • init(): Always returns a fully initialized instance.
    • init?(): Returns an optional instance, which can be nil if initialization fails.
  2. Use Cases:

    • init(): Used when you are certain that the initialization will always succeed.
    • init?(): Used when there is a possibility that the initialization might fail due to invalid input or other conditions.
  3. Error Handling:

    • init(): Does not handle errors internally; it assumes all inputs are valid.
    • init?(): Handles errors by returning nil, allowing the caller to handle the failure case.

Practical Example

Consider a scenario where you want to create a Person struct, but the name must not be empty:

swift Copy
struct Person {
    var name: String
    init?(name: String) {
        guard !name.isEmpty else {
            return nil
        }
        self...
expert

expert

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

expert

Explain how that code will behave for different Swift versions?

senior

Is there a way to create an abstract class in Swift?

junior

What is the difference between Upcast and Downcast in Swift?

Bình luận

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

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