Swift: How to use sizeof?

后端 未结 5 1628
逝去的感伤
逝去的感伤 2020-11-29 18:34

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

5条回答
  •  既然无缘
    2020-11-29 18:51

    Swift 4

    From Xcode 9 onwards there is now a property called .bitWidth, this provides another way of writing sizeof: functions for instances and integer types:

    func sizeof(_ int:T) -> Int {
        return int.bitWidth/UInt8.bitWidth
    }
    
    func sizeof(_ intType:T.Type) -> Int {
        return intType.bitWidth/UInt8.bitWidth
    }
    
    sizeof(UInt16.self) // 2
    sizeof(20) // 8
    

    But it would make more sense for consistency to replace sizeof: with .byteWidth:

    extension FixedWidthInteger {
        var byteWidth:Int {
            return self.bitWidth/UInt8.bitWidth
        }
        static var byteWidth:Int {
            return Self.bitWidth/UInt8.bitWidth
        }
    }
    
    1.byteWidth // 8
    UInt32.byteWidth // 4
    

    It is easy to see why sizeof: is thought ambiguous but I'm not sure that burying it in MemoryLayout was the right thing to do. See the reasoning behind the shifting of sizeof: to MemoryLayout here.

提交回复
热议问题