Coder1000 Coder1000 - 6 months ago 10
Swift Question

Casting the same code in Objective-C gives another numerical result

EDIT AND SOLUTION:



I realised just after asking the question: Xcode had automatically changed my code to cast to (long) in my
NSLog
! That was why I was getting a different result !




Swift



let nowMillis = 1000 * self.timeIntervalSince1970
print(nowMillis)


nowMillis
is: 1461865916801.75

Objective-C



double nowMillis = 1000 * [self timeIntervalSince1970];
NSLog([NSString stringWithFormat:@"%ld", (long)nowMillis]);


nowMillis
is: -2147483648

self
is
NSDate *now = [[NSDate alloc] init];
in both cases.

Answer

The problem is not that the code produces a different result, but that you are printing it differently. Your Objective-C tries to convert double to long, but the value overflows.

If you print it without the conversion, you should get the same result:

double nowMillis = 1000 * [self timeIntervalSince1970];
NSLog([NSString stringWithFormat:@"%f", nowMillis]);