Featured image of post == Equal to Operator

== Equal to Operator

1
Int == Optional(Int) ❓❓❓ 이게 가능하다고!

오늘은 우리가 자주 사용하는 == 오퍼레이터에 대해 알아보자

공식문서에서는 이렇게 Equal to를 정의하고 있다.

1
static func == (lhs: Wrapped?, rhs: Wrapped?) -> Bool

왼쪽과 오른쪽의 옵셔널 타입을 비교하여 같은지를 Bool 값으로 반환한다.

You can also use this operator to compare a non-optional value to an optional that wraps the same type. The non-optional value is wrapped as an optional before the comparison is made.

In the following example, the numberToMatch constant is wrapped as an optional before comparing to the optional numberFromString:

non-optional Type인 경우 비교되기 전에 랩핑하여 비교하기 때문에 비교가 가능하다!

1
2
3
4
5
6
let numberToFind: Int = 23
let numberFromString: Int? = Int("23")      // Optional(23)
if numberToFind == numberFromString {
    print("It's a match!")
}
// Prints "It's a match!"

Reference

Swift Doc - ==(_:_:)