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
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.