Swift use sizeof with Int32 Array

2019-01-27 18:33发布

问题:

i want to get the Length of an Array with "sizeof". I tried everything. This is the error message: "[Int32] is not convertible to T.Type"

The Array has to be Int32.

var testArray: [Int32] = [2000,400,5000,400]
var arrayLength = sizeof(testArray)

回答1:

You can get the number of elements in an array simply with

let count = testArray.count

and the total number of bytes of its elements with

var arrayLength = testArray.count * sizeof(Int32)
// Swift 3:
var arrayLength = testArray.count * MemoryLayout<Int32>.size

sizeof is used with types and sizeofValue with values, so both

var arrayLength = sizeof([Int32])
var arrayLength = sizeofValue(testArray)

would compile. But that gives you the size of the struct Array, not the size of the element storage.



回答2:

In Xcode 8 with Swift 3 beta 6 there is no function sizeof (). But if you want, you can define one for your needs. The good news are, that this new sizeof function works as expected with your array.

let bb: UInt8 = 1
let dd: Double = 1.23456

func sizeof <T> (_ : T.Type) -> Int
{
    return (MemoryLayout<T>.size)
}

func sizeof <T> (_ : T) -> Int
{
    return (MemoryLayout<T>.size)
}

func sizeof <T> (_ value : [T]) -> Int
{
    return (MemoryLayout<T>.size * value.count)
}

sizeof(UInt8.self)   // 1
sizeof(Bool.self)    // 1
sizeof(Double.self)  // 8
sizeof(dd)           // 8
sizeof(bb)           // 1

var testArray: [Int32] = [2000,400,5000,400]
var arrayLength = sizeof(testArray)  // 16

You need all versions of the sizeof function, to get the size of a variable and to get the correct size of a data-type and of an array.

If you only define the second function, then sizeof(UInt8.self) and sizeof(Bool.self) will result in "8". If you only define the first two functions, then sizeof(testArray) will result in "8".