ios - 无法将类型 'int' 转换为 swift 2.0 中的预期类型 NSTimeInterval

标签 ios objective-c swift

我在 Objective-C 中有这个方法来返回发送到服务器的位置的时间戳。

-(NSDate *) toLocalTime
{
   NSTimeZone *tz = [NSTimeZone defaultTimeZone];
   NSInteger seconds = [tz secondsFromGMTForDate: [NSDate date]];
   return [NSDate dateWithTimeInterval: seconds sinceDate: [NSDate date]];
}  

这在 Obj-C 中完美运行 我已将其转换为 swift 2.0

func toLocalTime() -> NSDate {
    var tz : NSTimeZone = NSTimeZone.defaultTimeZone()
    var seconds: Int = tz.secondsFromGMTForDate(NSDate())
    return (NSDate(timeInterval: seconds, sinceDate: NSDate()))
} 

但是当我将其转换为 swift 2.0 时,此行会显示错误(如上文标题所述),因为变量 seconds 的类型为 Int,而应传递给 dateWithTimeInterval 的变量应为 NSTimeInterval。

Error:Cannot convert the type 'int' to expected type NSTimeInterval

错误行:return (NSDate(timeInterval: seconds, sinceDate: NSDate()))

请帮忙!

最佳答案

如果你检查 Date 类 .. 你会发现 public typealias NSTimeInterval = Double 表示 NSTimeInterval 的返回类型是 Double ..

方法是

public convenience init(timeInterval secsToBeAdded: NSTimeInterval, sinceDate date: NSDate)  
// timeInterval -> return NSTimeInterval 
// date          -> return NSDate 

timeInterval 采用 Double 而不是 int ...所以只需将其转换为 Double 即可

 func toLocalTime() -> NSDate {
    let tz  = NSTimeZone.defaultTimeZone()
    let seconds = tz.secondsFromGMTForDate(NSDate())
    return (NSDate(timeInterval: Double(seconds), sinceDate: NSDate()))
 } 

关于ios - 无法将类型 'int' 转换为 swift 2.0 中的预期类型 NSTimeInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36027791/

相关文章:

ios - TableView 与 TextView : go to next Textview?

iphone - 在缩放的 MKMapView 上合并注释

ios - Swift:创建具有不同自定义类型的数组

swift - CAKeyframeAnimation doesNotRecognizeSelector

ios - 运行此代码时如何以及为何会出现信号 SIGABRT?

C# Xamarin - Popover segue 导致匿名构建错误

ios 7自定义转换不适用于导航 Controller

ios - 隐藏 View 并使用自动布局重新定位其他 View

html - 如何修复 webview 中调整视频 HTML 的大小?

iphone - 如何打开标准电话号码 View Controller