Coder1000 Coder1000 - 6 months ago 9
Swift Question

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

EDIT: I realised just after asking the question: Xcode automatically changed my code to cast to (long)!



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]);
Comments