Swift 스위치 명령문보다 작거나
switch
Swift의 문장에 익숙 하지만이 코드를 다음으로 대체하는 방법이 궁금합니다 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
그리고 RangeExpression
S ' contains(_:)
방법
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 { }
표준 라이브러리 참조를 살펴보면 ~=
오버로드가 무엇 을 수행 하는지 정확하게 알 수 있습니다 : 포함은 범위 일치 및 동일 항목과 동일합니다. (포함되지 않은 enum-case matching은 std lib의 함수가 아닌 언어 기능입니다)
왼쪽의 직선 부울과 일치하지 않는 것을 볼 수 있습니다. 이러한 종류의 비교를 위해서는 where 문을 추가해야합니다.
Unless... you overload the ~=
operator yourself. (This is generally not recommended) One possibility would be something like this:
func ~= <T> (lhs: T -> Bool, rhs: T) -> Bool {
return lhs(rhs)
}
So that matches a function that returns a boolean on the left to its parameter on the right. Here's the kind of thing you could use it for:
func isEven(n: Int) -> Bool { return n % 2 == 0 }
switch 2 {
case isEven: print("Even!")
default: print("Odd!")
}
For your case, you might have a statement that looks like this:
switch someVar {
case isNegative: ...
case 0: ...
case isPositive: ...
}
But now you have to define new isNegative
and isPositive
functions. Unless you overload some more operators...
You can overload normal infix operators to be curried prefix or postfix operators. Here's an example:
postfix operator < {}
postfix func < <T : Comparable>(lhs: T)(_ rhs: T) -> Bool {
return lhs < rhs
}
This would work like this:
let isGreaterThanFive = 5<
isGreaterThanFive(6) // true
isGreaterThanFive(5) // false
Combine that with the earlier function, and your switch statement can look like this:
switch someVar {
case 0< : print("Bigger than 0")
case 0 : print("0")
default : print("Less than 0")
}
Now, you probably shouldn't use this kind of thing in practice: it's a bit dodgy. You're (probably) better off sticking with the where
statement. That said, the switch statement pattern of
switch x {
case negative:
case 0:
case positive:
}
or
switch x {
case lessThan(someNumber):
case someNumber:
case greaterThan(someNumber):
}
Seems common enough for it to be worth considering.
You can:
switch true {
case someVar < 0:
print("less than zero")
case someVar == 0:
print("eq 0")
default:
print("otherwise")
}
Since someone has already posted case let x where x < 0:
here is an alternative for where someVar
is an Int
.
switch someVar{
case Int.min...0: // do something
case 0: // do something
default: // do something
}
And here is an alternative for where someVar
is a Double
:
case -(Double.infinity)...0: // do something
// etc
This is how it looks like with ranges
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"
}
The <0
expression doesn't work (anymore?) so I ended up with this:
Swift 3.0:
switch someVar {
case 0:
// it's zero
case 0 ..< .greatestFiniteMagnitude:
// it's greater than zero
default:
// it's less than zero
}
Glad that Swift 4 addresses the problem: As a workaround in 3 I did:
switch translation.x {
case 0..<200:
print(translation.x, slideLimit)
case -200..<0:
print(translation.x, slideLimit)
default:
break
}
Works but not ideal
참고URL : https://stackoverflow.com/questions/31656642/lesser-than-or-greater-than-in-swift-switch-statement
'Programing' 카테고리의 다른 글
확인란이 선택되어 있으면 (0) | 2020.07.08 |
---|---|
현재 컨트롤러보기 (0) | 2020.07.08 |
이산 x 스케일의 순서 변경 (0) | 2020.07.08 |
비활성화 된 UIButton이 희미하거나 회색이 아닙니다 (0) | 2020.07.08 |
부트 스트랩 3 Chevron 아이콘으로 쇼 상태 축소 (0) | 2020.07.08 |