0

我即将使用 AlamofireObjectMapper 扩展来映射来自服务器的 JSON 响应并创建一个函数来返回对象

我写了这些代码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 = () -> ()

我不知道为什么 funcdownloadPokemonDetails1给出错误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"]
    }
}
4

1 回答 1

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
        }
})

在您的代码中,您尝试从块中返回值,而不是从您的函数中返回值。我认为更好的方法是使用块返回口袋妖怪对象。

希望对你有帮助

于 2016-04-14T07:50:40.313 回答