Swift: gettimeofday and Unsafe Pointers
Asked Answered
B

1

3

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!

Baptiste answered 9/7, 2014 at 13:36 Comment(3)
What are you trying to achieve? let now = NSDate() is simpler...Takeover
If I remember correctly, NSDate was too slow and/or inaccurate when I first coded the UIGestureRecognizer I use this in. I don't know if that would still be the case now, but I don't know if I want to test it at this point (converting my app to Swift, enough other problems)Baptiste
UIEvents come with a .timestamp which is sub-millisecond. I guess if you need the microseconds then timval gives that.Takeover
B
8

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.

Breeching answered 9/7, 2014 at 13:53 Comment(6)
That was the first code I used, I didn't think about initialization though /facepalm/. Is the reason for needing it initialized that this is not a fully swift-ized method?Baptiste
Well it actually makes sense to me. If you don't initialize it then there is no memory reserved for the struct and &time points to nowhere so gettimeofday() can't use the address to alter the struct.Breeching
Yes, that does make perfect sense. Thanks again!Baptiste
@solenoid: I do not think that "reserving the memory" is the problem here. But Swift requires that every variable is initialized before it is used.Haim
@solenoid: That's not true though, is it? I can define a variable with var myNil: String? and then use it everywhere where I would normally use an Optional like myFooFunction(withOptionalStringParameter: myNil)Breeching
@Baptiste beause it needs to write to somewhere, it can only write to an allocated bit of memory, by instantiating timeval you align this allocated bit of memory to the specific data structure for a later use.Gilges

© 2022 - 2024 — McMap. All rights reserved.