user3766930
user3766930

Reputation: 5829

Why I cannot pass the correct argument to my static function in Swift?

I found a function for parsing date and time here: https://gist.github.com/jacks205/4a77fb1703632eb9ae79#file-timeago-swift and I've decided to use it in my project. I copied it into a new class and added a shared instance:

class DateCalculation {
    static let sharedInstance = DateCalculation()

    func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
        let calendar = NSCalendar.currentCalendar()
        let now = NSDate()
        let earliest = now.earlierDate(date)
        (...)

now when I'm using it in another place in the code I'm doing:

DateCalculation.timeAgoSinceDate(created_at);

and in this case created_at is a type of NSDate. But I'm getting error:

cannot convert value of type NSDate to expected argument type DateCalculation

what's the problem here?

Upvotes: 1

Views: 501

Answers (1)

Sulthan
Sulthan

Reputation: 130072

Your call should have the following form:

DateCalculation.sharedInstance.timeAgoSinceDate(created_at)

You are not calling a static method, you are calling an instance method on a singleton.

Also note that your definition has two parameters and you are calling it with just once parameter (you can also make the second parameter optional by assigning it a default value, e.g numericDates:Bool = true)

Another option is to just declare the method as class, if you are not using any instance variable:

class func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {

Upvotes: 7

Related Questions