-3

I am getting the error of "Unexpected non-void return value in void function in swift". and how to call this function. i want the return string and want to pass that as parameter. please see my below code

static func truetime() -> String? {

        let client = TrueTimeClient.sharedInstance
        //client.start()
        client.fetchIfNeeded { result in
            switch result {
            case let .success(referenceTime):
                let now = referenceTime.now()
                //print("Time is " + "\(now)")
                let dateFormatter : DateFormatter = DateFormatter()
                dateFormatter.dateFormat = "\(KeyValues.datetimeformat)"
                dateFormatter.timeZone = TimeZone(abbreviation: "GMT+05:00")
                let dateString = dateFormatter.string(from: now)

                print("Time is " + "\(dateString)")
                return dateString
            case let .failure(error):
                print("Error! \(error)")
            }
        }

    }
Umair Ahmad
  • 21
  • 2
  • 11
  • `client.fetchIfNeeded { result in … }` is a closure (like an inline function) that has a void return type. `return dateString` is attempting to return a `String` which is not allowed. – Jeffery Thomas Jul 10 '18 at 11:13

1 Answers1

0

This

return dateString

glitches with the inner completion void return , you need to use completion for asynchronous tasks

//

static func truetime(completion:@escaping(_ dateString:String?) -> Void ){

    let client = TrueTimeClient.sharedInstance
    //client.start()
    client.fetchIfNeeded { result in
        switch result {
        case let .success(referenceTime):
            let now = referenceTime.now()
            //print("Time is " + "\(now)")
            let dateFormatter : DateFormatter = DateFormatter()
            dateFormatter.dateFormat = "\(KeyValues.datetimeformat)"
            dateFormatter.timeZone = TimeZone(abbreviation: "GMT+05:00")
            let dateString = dateFormatter.string(from: now)

            print("Time is " + "\(dateString)")
            completion(dateString)
        case let .failure(error):
            print("Error! \(error)")
            completion(nil)
        }
    }

}

Use it like this

className.truetime { (dateString) in

   if let date = dateString {


   }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87