我即将使用AlamofireObjectMapper扩展来映射来自服务器的JSON响应并创建一个func来返回对象
我已经编写了func
func downloadPokemonDetails1(completed: DownloadComplete)-> (Pokemon?) {
let url = NSURL(string: _pokemonUrl)!
Alamofire.request(.GET, url).responseObject { (response: Response<Pokemon, NSError>) in
guard response.result.isSuccess else {
print(response.result.error.debugDescription)
return
}
let pokemon1 = response.result.value
return pokemon1
}
}
Herer是我的Constanst.swift(包含DownloadComplete
闭包)
import Foundation
let URL_BASE = "http://pokeapi.co"
let URL_POKEMON = "/api/v1/pokemon/"
typealias DownloadComplete = () -> ()
我不知道为什么func downloadPokemonDetails1
会给出错误un-expected Non-void return value in void function
我的Pokemon
班级
lass Pokemon: Mappable {
var id: String?
var name: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
name <- map["name"]
id <- map["id"]
}
}
答案 0 :(得分:2)
您的代码应该是这样的:
func downloadPokemonDetails1(completed: (Pokemon?) -> ()) {
let url = NSURL(string: _pokemonUrl)!
Alamofire.request(.GET, url).responseObject { (response: Response<Pokemon, NSError>) in
guard response.result.isSuccess else {
print(response.result.error.debugDescription)
return
}
let pokemon1 = response.result.value
completed(pokemon1)
}
}
self.downloadPokemonDetails1({
[weak weakSelf = self]
pokemon in
if let unwrappedPokemon = pokemon {
weakSelf.label.text = unwrappedPokemon.name
} else {
//show some error
}
})
在您的代码中,您尝试从块返回值,而不是从函数返回值。我认为更好的方法是使用块返回pokemon对象。
希望对你有帮助