Swift: gettimeofday and Unsafe Pointers

2019-02-28 22:34发布

问题:

The code in Swift

...
var time:timeval?
gettimeofday(UnsafePointer<timeval>, UnsafePointer<()>) // this is the method expansion before filling in any data
...

The code in Objective C

...
struct timeval time;
gettimeofday(&time, NULL);
...

I have been trying to find more information on UnsafePointer and alternatives to passing NULL, but I may be barking up the wrong tree.

If anyone knows how to get the equivilant code working in Swift, that would be great. If there is a good explanation of what's going on with it that would be even better!

回答1:

I know one way to do it and this is as follows:

var time:timeval = timeval(tv_sec: 0, tv_usec: 0)
gettimeofday(&time, nil)

I had to initialize time with something so there actually was a struct at the address &time pointed to.