1

I have written this code (In the function I am using the SwiftSky Api)

// Asked question about WEATHER

public func weatherQuestion(question: String, userLatitude: Double, userLongitude: Double) -> String {

 var answer = String()

// Setting up SwiftSky

 SwiftSky.secret ="...."

 SwiftSky.language = .italian

 SwiftSky.locale = .current

 SwiftSky.units.temperature = .celsius
 SwiftSky.units.accumulation = .centimeter
 SwiftSky.units.distance = .kilometer
 SwiftSky.units.precipitation = .millimeter
 SwiftSky.units.pressure = .millibar
 SwiftSky.units.speed = .kilometerPerHour

 if question.contains("meteo") {

     SwiftSky.get([.current, .alerts, .days, .hours, .minutes], at:  Location(latitude: userLatitude, longitude: userLongitude) , on: Date() , { (result) in

         switch result {

         case .success(let forecast):

             answer = (forecast.current?.summary)!

         case .failure(let error):

             print(error)

         }

     })

 }

 return answer
}

The problem is that, when I try to use the result of the function by printing its value (using the code below)

print(weatherQuestion(question: text, userLatitude: Double(self.locationCoordinates.latitude), userLongitude: Double(self.locationCoordinates.longitude)))

it doesn't print anything. How can I use the result of the function so that when I print out the value it is not empty?

4
  • 2
    SwiftSky works asynchronously. You cannot return something in a function from an asynchronous task. You have to add a completion handler. Commented Sep 3, 2017 at 10:36
  • how can I do it? @vadian (Sorry but I am new to programming) Commented Sep 3, 2017 at 10:36
  • 1
    Please look at (for example, there are many many similar answers) stackoverflow.com/questions/39643334/… Commented Sep 3, 2017 at 10:39
  • @Moritz You're right, I knew about it... 😂. Thank you all for the help Commented Sep 3, 2017 at 10:41

1 Answer 1

1

SwiftSky.get works async and calls the passed closure with the result parameter when operation is done. So, weatherQuestion returns immediately.

Change method signature to:

public func weatherQuestion(question: String, userLatitude: Double, userLongitude: Double, completion: (String) -> Void)

and call it:

case .success(let forecast):
     completion(forecast.current!.summary)

Now print in completion:

weatherQuestion(question: text, userLatitude: Double(self.locationCoordinates.latitude), userLongitude: Double(self.locationCoordinates.longitude), completion: { answer in
      print(answer)
})
Sign up to request clarification or add additional context in comments.

1 Comment

It works flawlessly! Thank you so much for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.