gpt4 book ai didi

Swift:如何使用 sizeof?

转载 作者:IT王子 更新时间:2023-10-29 05:00:12 27 4
gpt4 key购买 nike

为了在使用 Swift 时与 C API 集成,我需要使用 sizeof 函数。在 C 中,这很容易。在 Swift 中,我陷入了类型错误的迷宫中。

我有这个代码:

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

第二行有错误“‘NSNumber’不是‘T.Type’的子类型”。为什么会这样,我该如何解决?

最佳答案

针对 Swift 3 进行了更新

注意MemoryLayout<T>.size意味着不同于 sizeof 的东西在 C/Obj-C 中。您可以阅读这个旧线程 https://devforums.apple.com/message/1086617#1086617

Swift 使用泛型来明确表示该数字在编译时已知。

总而言之,MemoryLayout<Type>.size是单个实例所需的空间,而 MemoryLayout<Type>.stride是连续数组中连续元素之间的距离。 MemoryLayout<Type>.stride在 Swift 中与 sizeof(type) 相同在 C/Obj-C 中。

举个更具体的例子:

struct Foo {
let x: Int
let y: Bool
}

MemoryLayout<Int>.size // returns 8 on 64-bit
MemoryLayout<Bool>.size // returns 1
MemoryLayout<Foo>.size // returns 9
MemoryLayout<Foo>.stride // returns 16 because of alignment requirements
MemoryLayout<Foo>.alignment // returns 8, addresses must be multiples of 8

关于Swift:如何使用 sizeof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24662864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com