TomSawyer TomSawyer - 1 year ago 53
Swift Question

Swift: What's wrong with this math function?

I'm trying to create a variable with this Unixtime value but has

error. I really don't know why!

func Unixtime()->Int {
return Int(NSDate().timeIntervalSince1970)

It works on the Playground but failed to run if i put it in any project!
What's wrong?


The size of Int is 32-bit on 32-bit platforms (e.g. iPhone 5 and below), but the timestamp nowadays is in the range 0x57300000, which will certainly overflow when you multiply it by 2. In Swift arithmetic overflow will cause the program to crash.

You could force the output to be an Int64, or just return an NSTimeInterval (a Double) if you don't require the output to be an integer.

func Unixtime() -> NSTimeInterval {
    return NSDate().timeIntervalSince1970
print((Unixtime() + 2) * 2)