user1021430 user1021430 - 3 months ago 17
Swift Question

Swift: How to use sizeof?

In order to integrate with C API's while using Swift, I need to use the sizeof function. In C, this was easy. In Swift, I am in a labyrinth of type errors.

I have this code:

var anInt: Int = 5
var anIntSize: Int = sizeof(anInt)


The second line has the error "'NSNumber' is not a subtype of 'T.Type'". Why is this and how do I fix it?

Answer

Use sizeof as follows:

let size = sizeof(Int)

sizeof uses the type as the parameter.

If you want the size of the anInt variable you can pass the dynamicType field to sizeof.

Like so:

var anInt: Int = 5
var anIntSize: Int = sizeof(anInt.dynamicType)

Or more simply (pointed out by user102008):

var anInt: Int = 5
var anIntSize: Int = sizeofValue(anInt)
Comments