[iOS] ~= Operator

Eugenie·2022년 7월 14일
0

~=

~= 연산자는
값이 범위에 포함되는지 여부를 나타내는 Bool 값을 반환한다.

static func ~= (pattern: Self, value: Self.Bound) -> Bool

🎾 Parameters

🥏 pattern : 범위
🥏 bound: 범위에 포함되는지 확인할 값

범위 값 ~= 범위에 포함되는지 확인할 값

왼쪽에서 정의한 범위 값 안에 오른쪽의 값이 속하면 true, 아니라면 false 반환한다.

// example1
if a >= 0 && a <= 10 {

}

// example2
if 0...10 ~= a {

}

위의 example2example1~= 연산자를 이용하여 표현한 것이다.

💡 switch 구문의 case 의 범위를 확인할 때, ~= 연산자가 내부적으로 사용된다.

~= 연산자를 재정의하면
서로 다른 타입도 switch 연산으로 처리할 수 있다.

struct Person {
    let name : String
}

func ~=(pattern: String, value: Person) -> Bool {
    return value.name == pattern
}

let person = Person(name: "eugenie")

switch person {
case "eugenie":
    print("Hello eugenie!")
default:
    print("Sorry")
}
// Output: "Hello eugenie!"

if case "eugenie" = person {
    print("Hello eugenie!")
}
// Output: "Hello eugenie!"

배열의 index 값을 안전하게 처리할 수 있다.

extension Array {
	subscript(safe index: Int) -> Element? {
    	return indics ~= Index ? self[index] : nil
    }
}

📚 Reference
~=(::)
[Swift] ~=연산자
~= 연산자 in Swift
[iOS - swift] ~= 연산자 (범위 연산자)
[Swift] ~= 연산자

profile
🌱 iOS developer

0개의 댓글