8
Doing some pranks on the Playground, With Swift 2.2 we can declare constant
let testeIntOitoBits: Int8 = 127 //maximo - deveria ser 255
let testeIntOitoBits2: UInt8 = 255
Why can’t I store 255 in Int8 and Uint8 yes?
8
Doing some pranks on the Playground, With Swift 2.2 we can declare constant
let testeIntOitoBits: Int8 = 127 //maximo - deveria ser 255
let testeIntOitoBits2: UInt8 = 255
Why can’t I store 255 in Int8 and Uint8 yes?
9
You can use this to find out the maximum value of a type:
print(Int8.max) //vai responder 127
print(UInt8.max) //vai responder 255
I put in the Github for future reference.
Int8
is an integer marked type, that is, it has 8 bits and one of them is the signal if the number is positive or negative. Only 7 bits remain to represent the same number. With 7 bits we can only represent 128 different numbers, so it can only go from 0 to 127. In the case of negatives as it does not need to represent 0, it goes from -1 to -128. Totaling 256 different numbers (-128 to 127). If you have Int8.min
will receive a -128.
Already the UInt8
is an unmarked integer (the U
means unsigned) and you can use the 8 bits to represent the number, so you can represent from 0 to 255. Obviously you can’t represent negative numbers.
Avoid using unmarked types. Use only where you really need to and when you understand all the implications of yours. I reinforce this recommendation: it is rare to be useful to use an unmarked type. You will find that you need it, but it will probably be a wrong decision. When you’re sure you need to make sure you’ve understood all the differences of working with arithmetic in a type like this.
Browser other questions tagged swift objective-c typing
You are not signed in. Login or sign up in order to post.
very enlightening! Thank you very much!
– Mateus