Bit and byte
Essence
A bit is the smallest unit of information: 0 or 1. A byte is the smallest addressable unit of memory; on every modern platform, Apple's included, it is 8 bits, i.e. 256 (2⁸) possible values. Everything a program stores or sends — numbers, strings, images, pointers — is a sequence of bytes, and the type tells the compiler how to interpret those bytes.
In Swift
Int8/UInt8are exactly one byte,Int/UIntare word-sized (8 bytes on a 64-bit system),Int32,Int64are fixed-width.MemoryLayout<T>.sizeshows how many bytes a value occupies.- Bitwise operations:
&,|,^,~, shifts<</>>.OptionSetis built on them ([.alignLeft, .wrap]is just bits in one integer), as are flags, masks and hashes. - Literals:
0b1010(binary),0xFF(hex),1_000_000.
let a: UInt8 = 0b1010_0101 // 165
print(UInt8.max) // 255
print(MemoryLayout<Int>.size) // 8 on a 64-bit platform
print(MemoryLayout<Bool>.size) // 1 — even a single flag takes a whole byte
let flags: UInt8 = 0b0000_0101
print(flags & 0b100 != 0) // true — the third bit is set
print(flags << 1) // 10 — left shift = multiply by 2
print(Int8(bitPattern: 0xFF)) // -1 — same 8 bits, different interpretation
What the interviewer looks for
- Do you understand that the sign of a number is an interpretation convention (two's complement), not a property of the bytes.
- Do you know that
Intis platform-dependent, and that network and file formats need fixed-width types and an explicit byte order (bigEndian/littleEndian). - The link to memory: 1 KB = 1024 bytes, a 1000×1000 RGBA image takes 4 MB in memory regardless of the PNG file size.