0

I'm learning swift and caught in a situation:

I have a function which returns array. This function calls another closure inside and I want to pass the closure result as return to the function.

This is how my code has been setup

func setData() -> [City] {
  let conn = ApiConnection()
  conn.get_cities{  citiesList in
    return (citiesList)
  }
 }

When I do this I get error saying "Cannot convert return expression of type '()' to return type 'City?'"

Please advice how I can return the citiesList to my function

ash4
  • 101
  • 1
  • 11
  • Can you share the code of the API class also ? – Harjot Singh Apr 07 '19 at 07:22
  • `conn.get_cities` will be executing asynchronously - that is, the data is retrieved *after* `setData` has already returned. This means you can't return the array. You need to pass a closure to `setData` and then your `get_cities` closure can call *that* closure and pass the cities array. – Paulw11 Apr 07 '19 at 07:26

2 Answers2

1

If the closure get_cities is a non-escaping closure, then simply return the closure like

func setData() -> [City] {
    let conn = ApiConnection()
    return conn.get_cities{  citiesList in
        return (citiesList)
    }
}

If it is an escaping closure, then rather than returning a list from the function directly, use a completion handler like

func setData(completion: @escaping (([CityList]) -> Void)) {
    let conn = ApiConnection()
    conn.get_cities{  citiesList in
        completion(citiesList)
    }
}
Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
Jayant Jaiswal
  • 171
  • 1
  • 8
0

You cannot directly return the closure results. Closure results are meant to be full-filled later. To achieve this, you have to pass a closure which takes similar parameter.

func setData(completion: (([YOUR_CITY_CLASS]) -> void) ) {
    let conn = ApiConnection()
    conn.get_cities(completion)
}

NB: As this is an api call, most probably this is an closure which escapes, in that case the declaration of the function would be like following

func setData(completion: @escaping (([YOUR_CITY_CLASS]) -> void))
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44