programing

스위프트 스위치 문보다 작거나 큼

copysource 2023. 6. 4. 17:50
반응형

스위프트 스위치 문보다 작거나 큼

나는 잘 알고 있습니다.switch스위프트의 진술, 하지만 이 코드 조각을 어떻게 대체할지 궁금해합니다.switch:

if someVar < 0 {
    // do something
} else if someVar == 0 {
    // do something else
} else if someVar > 0 {
    // etc
}

한 가지 접근법이 있습니다.가정하면someVar이다.Int혹은 그 밖의Comparable선택적으로 피연산자를 새 변수에 할당할 수 있습니다.이렇게 하면 사용자가 원하는 대로 범위를 지정할 수 있습니다.where키워드:

var someVar = 3

switch someVar {
case let x where x < 0:
    print("x is \(x)")
case let x where x == 0:
    print("x is \(x)")
case let x where x > 0:
    print("x is \(x)")
default:
    print("this is impossible")
}

이는 다음과 같이 단순화할 수 있습니다.

switch someVar {
case _ where someVar < 0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
case _ where someVar > 0:
    print("someVar is \(someVar)")
default:
    print("this is impossible")
}

당신은 또한 피할 수 있습니다.where키워드 전체가 범위 일치:

switch someVar {
case Int.min..<0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
default:
    print("someVar is \(someVar)")
}

Swift 5를 사용하면 if 문을 대체하기 위해 다음 스위치 중 하나를 선택할 수 있습니다.


#1 스위치 사용하기PartialRangeFrom그리고.PartialRangeUpTo

let value = 1

switch value {
case 1...:
    print("greater than zero")
case 0:
    print("zero")
case ..<0:
    print("less than zero")
default:
    fatalError()
}

#2 스위치 사용하기ClosedRange그리고.Range

let value = 1

switch value {
case 1 ... Int.max:
    print("greater than zero")
case Int.min ..< 0:
    print("less than zero")
case 0:
    print("zero")
default:
    fatalError()
}

#3 where 절과 함께 스위치 사용

let value = 1

switch value {
case let val where val > 0:
    print("\(val) is greater than zero")
case let val where val == 0:
    print("\(val) is zero")
case let val where val < 0:
    print("\(val) is less than zero")
default:
    fatalError()
}

#4 where 절 및 할당과 함께 스위치 사용_

let value = 1

switch value {
case _ where value > 0:
    print("greater than zero")
case _ where value == 0:
    print("zero")
case _ where value < 0:
    print("less than zero")
default:
    fatalError()
}

#5 스위치 사용하기RangeExpression의전의~=(_:_:)교환입니다.

let value = 1

switch true {
case 1... ~= value:
    print("greater than zero")
case ..<0 ~= value:
    print("less than zero")
default:
    print("zero")
}

#6 스위치 사용하기Equatable의전의~=(_:_:)교환입니다.

let value = 1

switch true {
case value > 0:
    print("greater than zero")
case value < 0:
    print("less than zero")
case 0 ~= value:
    print("zero")
default:
    fatalError()
}

#7 스위치 사용하기PartialRangeFrom,PartialRangeUpTo그리고.RangeExpressioncontains(_:)방법

let value = 1

switch true {
case (1...).contains(value):
    print("greater than zero")
case (..<0).contains(value):
    print("less than zero")
default:
    print("zero")
}

switch후드 아래에 있는 진술은 다음을 사용합니다.~=교환입니다.그래서 이것은:

let x = 2

switch x {
case 1: print(1)
case 2: print(2)
case 3..<5: print(3..<5)
default: break
}

이에 대한 데슈가:

if 1          ~= x { print(1) }
else if 2     ~= x { print(2) }
else if 3..<5 ~= x { print(3..<5) }
else {  }

표준 라이브러리 참조를 보면 오버로드되는 작업을 정확히 알 수 있습니다. 여기에는 범위 일치 및 동등한 작업에 대한 동일성이 포함됩니다.(stdlib의 함수가 아닌 언어 기능인 열거형 대소문자 일치는 포함되지 않음)

왼쪽에 있는 직선 부울과 일치하지 않는 것을 볼 수 있습니다.이러한 비교를 위해 where 문을 추가해야 합니다.

만약...당신은 과부하를 걸었습니다.~=직접 조작합니다.(일반적으로 권장되지 않음) 한 가지 가능성은 다음과 같습니다.

func ~= <T> (lhs: T -> Bool, rhs: T) -> Bool {
  return lhs(rhs)
}

왼쪽의 부울을 오른쪽의 파라미터로 반환하는 함수와 일치합니다.다음과 같은 용도로 사용할 수 있습니다.

func isEven(n: Int) -> Bool { return n % 2 == 0 }

switch 2 {
case isEven: print("Even!")
default:     print("Odd!")
}

이 경우 다음과 같은 문장이 있을 수 있습니다.

switch someVar {
case isNegative: ...
case 0: ...
case isPositive: ...
}

하지만 이제 당신은 새로운 것을 정의해야 합니다.isNegative그리고.isPositive기능들.더 많은 작업자를 오버로드하지 않는 한...

일반 infix 연산자를 curry 접두사 또는 postfix 연산자로 오버로드할 수 있습니다.다음은 예입니다.

postfix operator < {}

postfix func < <T : Comparable>(lhs: T)(_ rhs: T) -> Bool {
  return lhs < rhs
}

이 작업은 다음과 같습니다.

let isGreaterThanFive = 5<

isGreaterThanFive(6) // true
isGreaterThanFive(5) // false

이 기능을 이전 기능과 결합하면 스위치 문은 다음과 같이 표시됩니다.

switch someVar {
case 0< : print("Bigger than 0")
case 0  : print("0")
default : print("Less than 0")
}

자, 여러분은 이런 종류의 것을 실제로 사용하지 말아야 할 것입니다. 그것은 약간 수상쩍습니다.당신은 (아마도) 계속하는 것이 더 나을 것입니다.where진술.즉, 스위치 문 패턴은

switch x {
case negative:
case 0:
case positive:
}

또는

switch x {
case lessThan(someNumber):
case someNumber:
case greaterThan(someNumber):
}

고려할 가치가 있을 정도로 흔한 것 같습니다.

할 수 있는 일:

switch true {
case someVar < 0:
    print("less than zero")
case someVar == 0:
    print("eq 0")
default:
    print("otherwise")
}

이것이 범위가 있는 것처럼 보입니다.

switch average {
case 0..<40: //greater or equal than 0 and less than 40
    return "T"
case 40..<55: //greater or equal than 40 and less than 55
    return "D"
case 55..<70: //greater or equal than 55 and less than 70
    return "P"
case 70..<80: //greater or equal than 70 and less than 80
    return "A"
case 80..<90: //greater or equal than 80 and less than 90
    return "E"
case 90...100: //greater or equal than 90 and less or equal than 100
    return "O"
default:
    return "Z"
}

Swift 4가 문제를 해결하게 되어 기쁩니다.

3의 해결 방법으로 다음을 수행했습니다.

switch translation.x  {
case  0..<200:
    print(translation.x, slideLimit)
case  -200..<0:
    print(translation.x, slideLimit)
default:
    break
}

효과는 있지만 이상적이지는 않습니다.

누군가 이미 게시했기 때문에case let x where x < 0:여기 어디에 대한 대안이 있습니다.someVar입니다.Int.

switch someVar{
case Int.min...0: // do something
case 0: // do something
default: // do something
}

그리고 여기 어디에 대한 대안이 있습니다.someVar입니다.Double:

case -(Double.infinity)...0: // do something
// etc

스위프트 5는 지금 멋지고 깨끗합니다.

switch array.count {
case 3..<.max: 
    print("Array is greater than or equal to 3")
case .min..<3:
    print("Array is less than 3")
default:
    break
}

<0표현이 작동하지 않습니다(더 이상?). 그래서 저는 이렇게 되었습니다.

Swift 3.0:

switch someVar {
    case 0:
        // it's zero
    case 0 ..< .greatestFiniteMagnitude:
        // it's greater than zero
    default:
        // it's less than zero
    }

내가 생각할 수 있는 가장 깨끗한 해결책:

switch someVar {
case ..<0:
    // do something
case 0:
    // do something else
default:
    // etc
}

언급URL : https://stackoverflow.com/questions/31656642/lesser-than-or-greater-than-in-swift-switch-statement

반응형