[Swift] "~= " 연산자 함수로 패턴 매칭 확인하기
Xcode에서 SubString에 대한 Definition을 찾던 중 신기한 연산자(!)를 발견했다.
여기서 ~=가 연산자인 것 같은데 뭔지 궁금해서 블로그를 작성하게 되었다.
📌 애플 개발자 공식 문서
~=(::) | Apple Developer Documentation
선언
~= 연산자는 pattern과 bound를 매개변수로 받고 부울(Bool)을 반환하는 함수이다.
static func ~= (pattern: Self, value: Self.Bound) -> Bool
매개변수
pattern → 어떠한 범위(a range)
bound → 패턴에 대응하는 값(a value to match against pattern)
논의
You can use the pattern-matching operator (~=) to test whether a value is included in a range. The pattern-matching operator is used internally in case statements for pattern matching. The following example uses the ~= operator to test whether an integer is included in a range of single-digit numbers:
번역) 패턴 매칭 연산자 (~=)는 어떠한 범위에서 원하는 값이 포함되어 있는지 아닌지를 테스트하기 위해 사용할 수 있다. 패턴 매칭 연산자는 case 구문에서 내부적으로 패턴 매칭을 위해 사용된다. 아래의 예시는 ~= 연산자를 하나의 정수가 한 자리 숫자의 범위에 포함되어 있는지 테스트하기 위해 사용하고 있다.
let aNumber = 3
if 0..<10 ~= aNumber {
print("\\(aNumber) is a single digit.")
}
// Prints "3 is a single digit."