Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate from Swift 2.3 to Date from Swift 3 Conversion

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

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!
  }
}

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!
  }
}

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!
  }
}

But now Xcode says Cannot convert value of type 'Date?' to type 'NSDate?' in coercion

How can I make this work?

like image 454
Charlie Pico Avatar asked Sep 19 '16 20:09

Charlie Pico


1 Answers

Well, this conversion is not the best work of the migrator ;-)

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
  }
}

The interval parameter seems to be mandatory even if it's not used.

like image 146
vadian Avatar answered Oct 22 '22 18:10

vadian