问题描述
所以我刚刚更新到Xcode 8,并将Swift 2.3代码转换为Swift 3,Swift 3将所有 NSDate
转换为 Foundation日期
So I've just updated to Xcode 8 and converted my Swift 2.3 code to Swift 3, and Swift 3 just converted all NSDate
to Foundation.Date
我有一个扩展名
为 NSDate
,现在称为 Foundation.Date
,看起来像这样:
And I had an extension
for NSDate
, now calledFoundation.Date
, it looked like this:
extension NSDate
{
var firstDayOfTheMonth:NSDate
{
var date: NSDate?
NSCalendar.currentCalendar().rangeOfUnit(.Month, startDate:&date , interval: nil, forDate: self)
return date!
}
}
Swift 3将其转换为:
And Swift 3 converted it to this:
extension Foundation.Date
{
var firstDayOfTheMonth:Foundation.Date
{
var date: Foundation.Date?
(Calendar.current as NSCalendar).range(of: .month, start:&date , interval: nil, for: self)
return date!
}
}
这里的问题是Xcode建议我这样做:不能将Date?类型的值转换为期望的参数类型NSDate?
并将&
The problem here is that Xcode suggests me to do this : Cannot convert value of type 'Date?' to expected argument type 'NSDate?'
and to drop the &
.
所以,我更改它,功能现在看起来像这样:
So, I change it and the function now looks like this:
extension Foundation.Date
{
var firstDayOfTheMonth:Foundation.Date
{
var date: Foundation.Date?
(Calendar.current as NSCalendar).range(of: .month, start:date as NSDate?, interval: nil, for: self)
return date!
}
}
但现在Xcode说不能转换Date?类型的值,以强制类型NSDate??/ / code $
But now Xcode says Cannot convert value of type 'Date?' to type 'NSDate?' in coercion
我该如何使这项工作? b $ b
How can I make this work?
推荐答案
嗯,这个转换不是迁移者最好的工作; - )
Well, this conversion is not the best work of the migrator ;-)
这是您的代码的Swift 3等价物
This is the Swift 3 equivalent of your code
extension Date
{
var firstDayOfTheMonth:Date
{
var date = Date()
var interval : TimeInterval = 0
Calendar.current.dateInterval(of: .month, start: &date, interval: &interval, for: self)
return date
}
}
interval
参数似乎是强制性的,即使没有使用。
The interval
parameter seems to be mandatory even if it's not used.
这篇关于NSDate从Swift 2.3转换为Swift 3转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!