使用函数的返回值 - Swift

时间:2017-09-03 10:31:18

标签: swift function

我已经编写了这段代码(在我正在使用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
}

问题在于,当我尝试通过打印其值来使用函数的结果时(使用下面的代码)

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

它不会打印任何东西。如何使用函数的结果,以便在打印出值时它不为空?

1 个答案:

答案 0 :(得分:1)

SwiftSky.get工作异步,并在操作完成时使用result参数调用传递的闭包。因此,weatherQuestion会立即返回。

将方法签名更改为:

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

并称之为:

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

现在打印完成:

weatherQuestion(question: text, userLatitude: Double(self.locationCoordinates.latitude), userLongitude: Double(self.locationCoordinates.longitude), completion: { answer in
      print(answer)
})