Optional Bool의 값 확인
Optional Bool이 true인지 확인하고 싶을 때이 작업이 작동하지 않습니다.
var boolean : Bool? = false
if boolean{
}
다음 오류가 발생합니다.
선택적 유형 '@IvalueBool?' 부울로 사용할 수 없습니다. 대신 '! = nil'테스트
nil을 확인하고 싶지 않습니다. 반환 된 값이 참인지 확인하고 싶습니다.
if boolean == true
Optional Bool로 작업하는 경우 항상해야 합니까?
Optionals가 BooleanType
더 이상 준수하지 않기 때문에 컴파일러가 Bool의 값을 확인하고 싶다는 것을 알지 못합니까?
선택적 부울을 사용하여 확인을 명시 적으로 만들어야합니다.
if boolean == true {
...
}
그렇지 않으면 선택 사항을 풀 수 있습니다.
if boolean! {
...
}
그러나 부울이 다음과 같은 경우 런타임 예외가 생성됩니다 nil
.
if boolean != nil && boolean! {
...
}
베타 5 이전에는 가능했지만 릴리스 노트에보고 된대로 변경되었습니다.
선택적 Bool 값으로 작업 할 때 혼동을 피하기 위해 옵션은 값이있을 때 더 이상 암시 적으로 true로 평가되지 않고 그렇지 않으면 false로 평가되지 않습니다. 대신 == 또는! = 연산자를 사용하여 nil에 대해 명시 적으로 검사하여 옵션에 값이 포함되어 있는지 확인하십시오.
부록 : @MartinR이 제안한대로 세 번째 옵션에 대한보다 간결한 변형은 병합 연산자를 사용하는 것입니다.
if boolean ?? false {
// this code runs only if boolean == true
}
즉, 부울이 nil이 아니면 표현식이 부울 값으로 평가되고 (즉, 래핑되지 않은 부울 값 사용), 그렇지 않으면식이 다음과 같이 평가됩니다. false
선택적 바인딩
스위프트 3 & 4
var booleanValue : Bool? = false
if let booleanValue = booleanValue, booleanValue {
// Executes when booleanValue is not nil and true
// A new constant "booleanValue: Bool" is defined and set
print("bound booleanValue: '\(booleanValue)'")
}
스위프트 2.2
var booleanValue : Bool? = false
if let booleanValue = booleanValue where booleanValue {
// Executes when booleanValue is not nil and true
// A new constant "booleanValue: Bool" is defined and set
print("bound booleanValue: '\(booleanValue)'")
}
코드는 let booleanValue = booleanValue
반환 false
경우 booleanValue
입니다 nil
과 if
블록이 실행되지 않습니다. 하면 booleanValue
되지 nil
,이 코드라는 새로운 변수 정의 booleanValue
유형 Bool
(대신, 선택의을 Bool?
).
Swift 3 & 4 코드 booleanValue
(및 Swift 2.2 코드 where booleanValue
)는 새 booleanValue: Bool
변수를 평가합니다 . 참이면 if
블록은 booleanValue: Bool
범위에서 새로 정의 된 변수로 실행됩니다 (옵션이 if
블록 내에서 바인딩 된 값을 다시 참조하도록 허용 ).
참고 : 바인딩 된 상수 / 변수의 이름을 .NET과 같은 선택적 상수 / 변수와 동일하게 지정하는 것은 Swift 규칙 let booleanValue = booleanValue
입니다. 이 기술을 가변 섀도 잉 이라고 합니다 . 관습에서 벗어나 let unwrappedBooleanValue = booleanValue, unwrappedBooleanValue
. 나는 무슨 일이 일어나고 있는지 이해하는 데 도움이되도록 이것을 지적합니다. 가변 섀도 잉을 사용하는 것이 좋습니다.
기타 접근법
병합 없음
이 특정 경우에는 병합이 명확하지 않습니다.
var booleanValue : Bool? = false
if booleanValue ?? false {
// executes when booleanValue is true
print("optional booleanValue: '\(booleanValue)'")
}
확인 false
이 명확하지 않습니다.
var booleanValue : Bool? = false
if !(booleanValue ?? false) {
// executes when booleanValue is false
print("optional booleanValue: '\(booleanValue)'")
}
참고 : if !booleanValue ?? false
컴파일되지 않습니다.
Force unwrapping optional (avoid)
Force unwrapping increases the chance that someone will make a change in the future that compiles but crashes at runtime. Therefore, I would avoid something like this:
var booleanValue : Bool? = false
if booleanValue != nil && booleanValue! {
// executes when booleanValue is true
print("optional booleanValue: '\(booleanValue)'")
}
A General Approach
Though this stack overflow question asks specifically how to check if a Bool?
is true
within an if
statement, it's helpful to identify a general approach whether checking for true, false or combining the unwrapped value with other expressions.
As the expression gets more complicated, I find the optional binding approach more flexible and easier to understand than other approaches. Note that optional binding works with any optional type (Int?
, String?
, etc.).
I found another solution, overloading the Boolean operators. For example:
public func < <T: Comparable> (left: T?, right: T) -> Bool {
if let left = left {
return left < right
}
return false
}
This may not be totally in the "spirit" of the language changes, but it allows for safe unwrapping of optionals, and it is usable for conditionals anywhere, including while loops.
참고URL : https://stackoverflow.com/questions/25523305/checking-the-value-of-an-optional-bool
'Nice programing' 카테고리의 다른 글
반사와 함께 '주조' (0) | 2020.10.15 |
---|---|
C의 구조 메모리 레이아웃 (0) | 2020.10.15 |
정적 및 최종 한정자가있는 이상한 Java 동작 (0) | 2020.10.15 |
LAMP 스택이란 무엇입니까? (0) | 2020.10.15 |
Angularjs에 다른 상수로 상수를 정의하는 방법이 있습니까? (0) | 2020.10.15 |