Better way to convert an int to a boolean
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
bool boolValue = intValue != 0;
Casting int to bool in C/C++
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
Converting Int to Bool
No, there is and has never been an explicit built in option for conversion of Int
to Bool
, see the language reference for Bool
for details.
There exists, still, however, an initializer by NSNumber
. The difference is that implicit bridging between Swift numeric type and NSNumber
has been removed in Swift 3 (which previously allowed what seemed to be explicit Bool
by Int
initialization). You could still access this by NSNumber
initializer by explicitly performing the conversion from Int
to NSNumber
:
let number = 1
let result = Bool(number as NSNumber)
print(result) // true
As @Hamish writes in his comment below: if we leave the subject of initializers and just focus on the end result (instantiating a Bool
instance given the value of an Int
instance) we can simply make use of the !=
operator for Int
values (specifically, the operator with signature func !=(lhs: Int, rhs: Int) -> Bool
), a generalization easily achievable using the !=
operator approach:
let number = -1
let result = number != 0
print(result) // true
Much like you yourself as well as @JAL describes in his answer, you could construct your own Bool
by Int
initializer, but you might as well consider generalizing this for any type conforming to the Integer
protocol:
extension Bool {
init<T: Integer>(_ num: T) {
self.init(num != 0)
}
}
/* example usage */
let num1: Int8 = -1
let num2: Int = 3
let num3: UInt64 = 0
// ....
let result1 = Bool(num1) // true
let result2 = Bool(num2) // true
let result3 = Bool(num3) // false
Why use !! when converting int to bool?
The problems with the "!!" idiom are that it's terse, hard to see, easy to mistake for a typo, easy to drop one of the "!'s", and so forth. I put it in the "look how cute we can be with C/C++" category.
Just write bool isNonZero = (integerValue != 0);
... be clear.
I am not able to convert int to boolean in Java in the following code
Not every type can be cast to another. int
to boolean
is one of those that is not permitted in Java. The Java Language Specification explains what is and what isn't possible.
Can't cast int to bool
int
and bool
can't be converted implicitly (in contrast to C++, for example).
It was a concious decision made by language designers in order to save code from errors when a number was used in a condition. Conditions need to take a boolean
value explicitly.
It is not possible to write:
int foo = 10;
if(foo) {
// Do something
}
Imagine if the developer wanted to compare foo with 20 but missed one equality sign:
if(foo = 20) {
// Do something
}
The above code will compile and work - and the side-effects may not be very obvious.
Similar improvements were done to switch
: you cannot fall from one case to the other - you need an explicit break
or return
.
Convert boolean to int in Java
int myInt = myBoolean ? 1 : 0;
^^
PS : true = 1 and false = 0
Cannot implictly convert type int to bool
i % 2
is of type int, not bool, C# cannot automatically make the conversion, so simply try:
i % 2 != 0
How to convert integer to boolean in C#
This will solve your error (having a bool
return type instead of the int
) and will make your code shorter:
public bool IsUserInRole(IsUserInRole userInRole)
{
return _userRepository.CheckIfUserIsInRole(userInRole) == 1;
}
Related Topics
Swift Error: Missing Argument Label 'Name:' in Call
Reversing the Order of a String Value
How to Detect a 'Click' Gesture in Swiftui Tvos
How to Get Date and Time to Show a Clock in Uilabel
Open a Viewcontroller from Remote Notification
Swift "Where" Array Extensions
How to Append a Character to a String in Swift
Swift: How to Change a Property's Value Without Calling Its Didset Function
How to Make Rounded Corner Progress Bar in Swift
Pass Optional Block or Closure to a Function in Swift
Calculate Area of Mkpolygon in an Mkmapview
Translucent Status Bar with No Navigation Bar
Find Item of Specific Type in Array
App Crash on Sign in (Xcode 9.3) Exc_Bad_Access (Code=1, Address=0X1)
Wait Until an Asynchronous API Call Is Completed - Swift/Ios
Need to Check That Braces in Given Array Are Balanced or Not