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!

solenoid
  • 954
  • 1
  • 9
  • 20
  • What are you trying to achieve? `let now = NSDate()` is simpler... – Grimxn Jul 09 '14 at 14:51
  • 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) – solenoid Jul 09 '14 at 15:39
  • `UIEvents` come with a `.timestamp` which is sub-millisecond. I guess if you need the microseconds then `timval` gives that. – Grimxn Jul 09 '14 at 17:59

1 Answers1

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.

Skyte
  • 529
  • 2
  • 9
  • 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? – solenoid Jul 09 '14 at 14:09
  • 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. – Skyte Jul 09 '14 at 14:18
  • Yes, that does make perfect sense. Thanks again! – solenoid Jul 09 '14 at 14:20
  • 1
    @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. – Martin R Jul 09 '14 at 14:58
  • @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) – Skyte Apr 11 '17 at 13:19
  • 1
    @solenoid 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. – George Maisuradze Aug 16 '18 at 13:23