Creating a time base info struct in C is easy, but in Swift the following does not work in the playground:
let timebaseInfo: mach_timebase_info_data_t = mach_timebase_info(&timebaseInfo)
The error is Variable used within its own initial value
I understand the error, but I am unable to think of a way to do this without dropping down to C. Is there a Swift only way that I am missing? Any help would be greatly appreciated. :-)
Edit: Actually I see "A" problem with the above, the "=" doesn't make sense. But I did try the following also:
let timebaseInfo: mach_timebase_info_data_t
mach_timebase_info(&timebaseInfo)'
With an error stating timebasedInfo used before initialization. :-(
The mach_timebase_info function is declared as
typealias mach_timebase_info_t = UnsafeMutablePointer<mach_timebase_info>
// ...
func mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t
which means that you can pass an (initialized) mach_timebase_info variable
as an "in-out expression" with &:
var timebaseInfo = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&timebaseInfo)
if status == KERN_SUCCESS {
// ...
}
For more information, see Interacting with C APIs in the "Using Swift with Cocoa and Objective-C" manual:
Mutable Pointers
When a function is declared as taking an
UnsafeMutablePointer<Type>argument, it can accept any of the following:
nil, which is passed as a null pointer- An
UnsafeMutablePointer<Type>value- An in-out expression whose operand is a stored lvalue of type
Type, which is passed as the address of the lvalue- An in-out
[Type]value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
You'll need to use UnsafeMutablePointer<Type>, as follows:
let p = UnsafeMutablePointer<mach_timebase_info_data_t>.alloc(1)
mach_timebase_info(&p.memory)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With