Josh O'Connor Josh O'Connor - 2 months ago 26
iOS Question

NSDate code not migrating to Swift 3.0

I am attempting to convert my code to Swift 3.0, and I am having difficulty converting a certain block of code after using the migration tool.

PREVIOUS TO SWIFT 3.0 MIGRATION:

import Foundation

extension NSDate {
convenience init(posixTime: Double) {
self.init(timeIntervalSince1970: Double(posixTime) / 1000.0)
}
}


AFTER MIGRATION TOOL:

extension Date {
init(posixTime: Double) {
//ERROR IN THE LINE BELOW: "'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type"
(self as NSDate).init(timeIntervalSince1970: Double(posixTime) / 1000.0)
}
}


I followed Xcodes advice to replace "init" with "type(of: init)":

extension Date {
init(posixTime: Double) {
//ERROR IN THE LINE BELOW: "Expected expression in list of expressions"
(self as NSDate).type(of: init)(timeIntervalSince1970: Double(posixTime) / 1000.0)
}
}


Xcode then asks me to add a comma in front of "of:", which leads to more errors (and more suggestions to put commas in the wrong places). What is the correct way to use this block of code in Swift 3?

Answer

You can easily remove the convenience from the init method.

extension Date {
    init(posixTime: Double) {
        self.init(timeIntervalSince1970: Double(posixTime) / 1000.0)
    }
}

Seems like the migration tool has incorrectly convert the self instance to NSDate in your previous code.