Bool.hashValue valid to convert to Int?
No, hashValue
is not a proper way to convert some other type to an Int
, especially if you want specific results.
From the documentation for Hashable hashValue
:
Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.
The simplest solution to convert a Bool
to Int
is:
let someInt = someBool ? 1 : 0
Converting Boolean value to Integer value in Swift
Swift 5
Bool -> Int
extension Bool {
var intValue: Int {
return self ? 1 : 0
}
}
Int -> Bool
extension Int {
var boolValue: Bool {
return self != 0
}
}
Convert boolean to int in Java
int myInt = myBoolean ? 1 : 0;
^^
PS : true = 1 and false = 0
Converting Boolean to Integer in Java without If-Statements
You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.
If you check the compiled code of that method (by the way, using return b ? 1 : 0;
compiles to the exact same instructions), you will see that it does not use a jump:
0x0000000002672580: sub $0x18,%rsp
0x0000000002672587: mov %rbp,0x10(%rsp) ;*synchronization entry
0x000000000267258c: mov %edx,%eax
0x000000000267258e: add $0x10,%rsp
0x0000000002672592: pop %rbp
0x0000000002672593: test %eax,-0x2542599(%rip) # 0x0000000000130000
; {poll_return}
0x00000000025b2599: retq
Note: this is on hotspot server 7 - you might get different results on a different VM.
Why Hash Code of different Boolean instances is always the same?
The JavaDoc of Boolean.hashCode()
method says:
Returns the integer
1231
if this object representstrue
; returns the integer1237
if this object representsfalse
.
How to safely load a hash, and convert a value to a boolean if it exists
Assuming that you are using the popular github.com/go-redis/redis package, the return value from HGetAll(key).Result()
is a map[string]string
(doc). The expression someMap["has_ended"]
evaluates to the empty string if the key is not present.
If hasEnded is true if and only if the key is present with the value "true", then use the following:
hasEnded := someMap["has_ended"] == "true"
Use strconv.ParseBool to a handle a wider range of possible values (1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False):
hasEnded, err := strconv.ParseBool(someMap["has_ended"])
if err != nil {
// handle invalid value or missing value, possibly by setting hasEnded to false
}
boolean value doesnt change insade class java
Ok so i finally find an answer. That was my ContactListener before i edited my post:
case BetterSnake.ENEMY_BIT | BetterSnake.PLAYER_TAIL_BIT:
if(fixA.getFilterData().categoryBits == BetterSnake.ENEMY_BIT) {
for(int i = 0; i < creator.getEnemies().size; i++) {
if(creator.getEnemies().get(i).equals( fixA.getUserData())) {
creator.getEnemies().removeIndex(i);
}
}
((Snake) fixA.getUserData()).setRemoveSnake(true);
}else {
for(int i = 0; i < creator.getEnemies().size; i++) {
if(creator.getEnemies().get(i).equals( fixB.getUserData())) {
creator.getEnemies().removeIndex(i);
}
}
((Snake) fixB.getUserData()).setRemoveSnake(true);
}
break;
And because i removed Snake from creator.getEnemies() list, my update method:
for(int i = 0; i < creator.getEnemies().size; i++) {
Snake enemy = creator.getEnemies().get(i);
enemy.update(dt);
}
didn't work and i simply couldn't remove Snake because Snake was removed from list and program didn't go thru enemy.update(dt).
Serializing custom bag object to json string int to Bool in swift
This is because Int
is bridged to NSNumber
and NSNumber
is always is Bool
.
In your case, you don't need these lines:
else if(propValue is Bool)
{
propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName!)
}
You can just delete them, because NSJSONSerialization
can handle it.
let flg:NSNumber = true
let id:NSNumber = 1
let dict:NSDictionary = [
"bool": flg,
"id": id
]
let jsonDat = NSJSONSerialization.dataWithJSONObject(dict, options: .allZeros, error: nil)!
let jsonStr = NSString(data: dat, encoding:NSUTF8StringEncoding)
// -> {"id":1,"bool":true}
more relevant example:
class Foo:NSObject {
var flg:Bool = true
var id:Int = 1
}
let obj = Foo()
let dict:NSDictionary = [
"flg": obj.valueForKey("flg")!,
"id": obj.valueForKey("id")!
]
let jsonData = NSJSONSerialization.dataWithJSONObject(dict, options: .allZeros, error: nil)!
let jsonStr = NSString(data: jsonData, encoding:NSUTF8StringEncoding)!
// -> {"flg":true,"id":1}
Related Topics
Swift 4 "Extra Argument in Call" Rxswift
Avaudiopcmbuffer Built Programmatically, Not Playing Back in Stereo
What Is The Advantage of Closure Stored Property Initialisation
Do Protocols Have an Effect on The Retain Count
Setadvertisertrackingenabled Is Not Found in Settings Class of Fbsdk
Swift Flatmap on Array with Elements Are Optional Has Different Behavior
Apple Mach-O Linker Error (Static, Not Ld)
Literal Numbers in Floatingpoint Protocol
How to Get My Button to Reflect The Bool of My Environmentobject
Covert Realm List to Realm Result
Swift - Nsdate - Remove Part of Date
How to Set a Custom Annotations for All Points Except for User Location
Swift Initialization Rule Confusion
Swiftsupport Folder Not Included in The IPA When Generating Build from Script
Convert Input Data to Integer in Swift
How to Find Multiple Nsrange for a String from Full String iOS Swift