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

What’s the difference between == and === ?

Câu trả lời

In Swift, == and === are used to compare values, but they serve different purposes and are used in different contexts.

== Operator

The == operator is used to check if two values are equal. This is a value comparison, meaning it checks if the data or content of the two variables is the same. It can be used with both value types (like Int, Double, Struct, etc.) and reference types (like Class).

Example:

swift Copy
let a = 10
let b = 10
if a == b {
    print("a and b are equal")
}

In this example, a and b are both integers with the same value, so a == b evaluates to true.

=== Operator

The === operator is used to check if two references point to the same instance of a class. This is a reference comparison, meaning it checks if the two variables refer to the exact same object in memory. It is only applicable to class instances, not value types.

Example:

swift Copy
class Car {
    var model: String
    init(model: String) {
        self.model = model
    }
}

let car1 = Car(model: "Toyota")
let car2 = car1
let car3 = Car(model: "Toyota")

if car1 === car2 {
    print("car1 and car2 refer to the same instance")
}

if car1 !== car3 {
    print("car1 and car3 ...
junior

junior

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

expert

Explain what is DispatchGroup?

senior

What is the difference between static func and class func in Swift?

expert

Explain usage of Concurrent vs Serial Queues with async and sync blocks

Bình luận

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

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