麻烦使用Swift NSDate“timeIntervalSinceNow”[重复]

时间:2023-01-23 22:15:11

This question already has an answer here:

这个问题在这里已有答案:

I've searched around and am flummoxed by this riddle.

我四处搜寻,被这个谜语搞得一团糟。

In Swift, Xcode 6.2, these lines work:

在Swift,Xcode 6.2中,这些行有效:

let day_seconds = 86400
let one_day_from_now = NSDate(timeIntervalSinceNow:86400)

But the following returns an error:

但以下返回错误:

let day_seconds = 86400
let one_day_from_now = NSDate(timeIntervalSinceNow:day_seconds)

Console output:

"Playground execution failed: /var/folders/4n/88gryr0j2pn318sw_g_mgkgh0000gn/T/lldb/10688/playground625.swift:24:30: error: extra argument 'timeIntervalSinceNow' in call let one_day_from_now = NSDate(timeIntervalSinceNow:day_seconds)"

“游乐场执行失败:/var/folders/4n/88gryr0j2pn318sw_g_mgkgh0000gn/T/lldb/10688/playground625.swift:24:30:错误:在调用中额外参数'timeIntervalSinceNow'让one_day_from_now = NSDate(timeIntervalSinceNow:day_seconds)”

What's going on here? Why the NSDate trickiness?

这里发生了什么?为什么NSDate棘手?

1 个解决方案

#1


6  

It's because timeIntervalSinceNow expect NSTimeInterval which is Double.

这是因为timeIntervalSinceNow期望NSTimeInterval是Double。

If you do:

如果你这样做:

let day_seconds = 86400

day_second is Int type which is not what the method expect. However when you type the number itself:

day_second是Int类型,它不是方法所期望的。但是,当您键入数字本身时:

let one_day_from_now = NSDate(timeIntervalSinceNow:86400)

compiler implicit that you are passing Double, because it's what the method expect, which is ok.

编译器暗示你传递Double,因为它是方法所期望的,这是好的。

The solution cancould be using NSTimeInterval(day_seconds) or Double(day_seconds) which is the same or when you declare constant make sure it's double, for example:

解决方案可以使用NSTimeInterval(day_seconds)或Double(day_seconds),它们是相同的,或者当你声明常量时确保它是double,例如:

let day_seconds = 86400.0

or

let day_seconds: Double = 86400

or

let day_seconds: NSTimeInterval = 86400

#1


6  

It's because timeIntervalSinceNow expect NSTimeInterval which is Double.

这是因为timeIntervalSinceNow期望NSTimeInterval是Double。

If you do:

如果你这样做:

let day_seconds = 86400

day_second is Int type which is not what the method expect. However when you type the number itself:

day_second是Int类型,它不是方法所期望的。但是,当您键入数字本身时:

let one_day_from_now = NSDate(timeIntervalSinceNow:86400)

compiler implicit that you are passing Double, because it's what the method expect, which is ok.

编译器暗示你传递Double,因为它是方法所期望的,这是好的。

The solution cancould be using NSTimeInterval(day_seconds) or Double(day_seconds) which is the same or when you declare constant make sure it's double, for example:

解决方案可以使用NSTimeInterval(day_seconds)或Double(day_seconds),它们是相同的,或者当你声明常量时确保它是double,例如:

let day_seconds = 86400.0

or

let day_seconds: Double = 86400

or

let day_seconds: NSTimeInterval = 86400