관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] 패턴 매칭(Pattern Matching) 개념 (Optional 패턴, Expression 패턴, switch 문과 ~= 연산자) 본문

iOS 기본 (swift)

[iOS - swift] 패턴 매칭(Pattern Matching) 개념 (Optional 패턴, Expression 패턴, switch 문과 ~= 연산자)

jake-kim 2022. 6. 22. 01:33

패턴 매칭) 많이 사용하는 익숙한 패턴

1) 바인딩

let age = (20, 34)

switch age {
case let (a1, a2): 
    print("\(a1), \(a2)")
default:
	break
}

2) 와일드 카드

switch age {
case let (a1, _): // '_' 와일드 카드 패턴
    print("\(a1), \(a2)")
default:
	break
}

3) 튜플

let (v1, v2) = (1, 2)
print(v1)
print(v2)

4) enum

enum MyEnum {
 case a(Int)
 case b
}

let myEnum = MyEnum.a(10)

if case let a(int) = myEnum {
	print(int)
}

패턴 매칭) 익숙하지 않은 패턴

1) 옵셔널 패턴

  • some 키워드를 이용하여 패턴을 매칭하고, 이 키워드를 사용하면 unwrapping도 자동으로 수행
let v1: Int? = 100
if case .some(let int) = v1 {
  print(int)
}
  • 보통 switch문에서 unwrapping 할때 사용
let v1: Int? = 100
switch v1 {
case let .some(int):
  print(int)
default:
  print("not")
}

2) 표현 패턴(Expression Pattern)

  • ~= 연산자의 결과가 true를 반환하여 매칭시키는 패턴
    • swift에서 디폴트로 구현되어있는 형태는 범위를 체크할 수 있는 형태로 구현되어 있음
let v = 7

if 0...10 ~= v {
  print("0 ~ 10")
} else {
  print("not contains")
}
  • switch 구문에서 내부적으로 사용되고 있는 패턴
switch 7 {
case 0...10:
  print("0 ~ 10")
default:
  print("not contains")
}
  • ~=를 오버라이딩하면 다르게 사용이 가능 
    • 인수 중 첫 번째 인수는 switch문의 case에 해당하는 값이오고, 두 번째 인수는 switch문의 condition에 해당하는 값
func ~= (caseValue: String, conditionValue: Int) -> Bool {
    return caseValue == "\(conditionValue)"
}

let myValue = 10

switch myValue {
case "1": 
  print("1")
case "10":
  print("10")
default:
  print("default")
}

// "10"

(만약 내부 class에서 해당 switch문에만 ~=를 재정의하고 싶은 경우, static func ~= 로 정의하여 사용)

 

* 참고

https://dongminyoon.tistory.com/37?category=419822

https://stackoverflow.com/q/47060366

Comments