If you like writing code in C, you may be familiar with sizeof. You would use it when allocating some memory, doing I/O operation or even calculating the size of an array. It is an operator in fact, and it could be applied on a type or an instance of some type, and return the size of it memory. The type of the returned value is called size_t, which is an int type independent of platforms. In Cocoa, some APIs need information about the memory size of a type or instance, this is the case we can use sizeof. A most common one is generating an NSData object from a C array. We have to pass the length of data to it. In Objective-C, sizeof is still there, so just do it:

    char bytes[] = {1, 2, 3};
    NSData *data = [NSData dataWithBytes:&bytes length:sizeof(bytes)];
    // <010203>

To make things clear, there are two versions of sizeof in C: one for a type, another for an instance or value:


However, different with C or Objective-C, in Swift, sizeof is wrapped in Swift. It is not an operator any more, but a function which could only accept type as parameter. There is another similar function sizeofValue, which takes a value as input, and returns its size. These two methods now return values of Int, instead of size_t:

func sizeof<T>(_: T.Type) -> Int

func sizeofValue<T>(_: T) -> Int

Although the name is similar, but the behaviors of sizeofValue is very diverse with the sizeof function. In Swift, sizeofValue will return the actual size of the input value, instead of the size of the content of it in memory. Take an example to explain what does this mean. If we want to represent the bytes in the above example, it would be [CChar]. In C or Objective-C, doing a sizeof on bytes will return the entire array content size in memory. That means if each char occupies 1 unit, and the array contains 3 chars, the result is 3 char unit. But in Swift, if we call sizeofValue with bytes, the result would be 8, which is the length of a reference to a 64-bit system:

// C
char bytes[] = {1, 2, 3};
// 3
// Swift
var bytes: [CChar] = [1,2,3]
// 8

Instead of using sizeofValue to get the length, we need some calculation. The equivalent Swift code of generating NSData above would be:

var bytes: [CChar] = [1,2,3]
let data = NSData(bytes: &bytes, length:sizeof(CChar) * bytes.count)

As an exercise, please point out the result of the code below, and try to explain it ```swift enum MyEnum: UInt16 { case A = 0 case B = 1 case C = 65536 }