我有下一个递归Promise函数调用:
func getPlaces(location: Location) -> Promise<[Geosearch]> {
return Promise().then {
URLSession.shared.dataTask(.promise, with: url)
}.compactMap { result in
let json = try JSONDecoder().decode(JsonPlaces.self, from: result.data)
let places = json.query.geosearch
return places
}
}
func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
return getPlaces(location).then{ places in //error here
if hasNonVisitedPlaces(places: places) {
return Promise.value(places)
} else {
return getPlaces(location)
}
}
}
func hasNonVisitedPlaces(places: [Geosearch]) -> Bool {
return places.count > 0
}
但是编译器编译失败,并显示错误“无法将类型'Promise <_。T>'的返回表达式转换为类型'Promise <[Geosearch]>'。错误在哪里?
似乎是编译器错误。 该函数已正确编译:
func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
return getPlaces(location).then{ places in
return Promise.value(places)
}
}
此功能也是如此:
func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
return getPlaces(location).then{ places in
return getPlaces(location)
}
}
但是此函数导致错误:
func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
return getPlaces(location).then{ places in //error here
if hasNonVisitedPlaces(places: places) {
return Promise.value(places)
} else {
return getPlaces(location)
}
}
}
答案 0 :(得分:0)
有时我们需要显式提供返回类型,因此请尝试以下操作。
func getAtLeastOnePlace(location: Location) -> Promise<[Geosearch]> {
return getPlaces(location).then{ places -> Promise<[Geosearch]> in
if hasNonVisitedPlaces(places: places) {
return Promise.value(places)
} else {
return getPlaces(location)
}
}
}