What's the difference between == and ===?
Swift에서도 스택을 사용하여 값을 저장하는 방식과 힙을 사용하여 참조를 전달하는 방식으로 나뉘어 있기 때문에 비교 연산자인 ==와 ===를 비교해보고자 한다.
일반 타입(string, int, float, double, boolean) 비교
let value1 = 42
let value2 = 42
print(value1 == value2) // true
print(value1 === value2) // error: argument type 'Int' expected to be an instance of a class or class-constrained type
컬렉션 타입(Array, Set, Dictionary) 비교
let reference1 = ["key": "value"]
let reference2 = referenceDictionary1
print(reference1 == reference2) // true
print(reference1 === reference2) // true
nil 비교
일반 타입(string, int, float, double, boolean) 비교와 같다
let nil1: String? = nil
let nil2: String? = nil
print(value1 == value2) // true
print(value1 === value2) // error: argument type 'String' expected to be an instance of a class or class-constrained type
Custom 타입 비교
Equatable Protocol을 준수해야한다
class IntegerRef: Equatable {
let value: Int
init(_ value: Int) {
self.value = value
}
// 아래 부분이 없다면 Compile Error
static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool {
return lhs.value == rhs.value
}
}
let value1 = IntegerRef(100)
let value2 = IntegerRef(100)
print(value1 == value2) // true
출처
Last updated