无法在完成处理程序中将类型'()'的值分配给类型'[Category]'

时间:2019-07-16 14:12:22

标签: swift model alamofire

我已经创建了一个Servicemodel类作为单例,以便在我想使用getcategories方法时从Viewcontroller中的服务器中获取数据(我使用Alamofire )我遇到错误无法分配类型的值'()'键入'[Category]'

class ServiceModel {

    static let shared = ServiceModel()
    var categories = [Category]()

    func getcategories(completion:@escaping([Category]) -> ()){
        Alamofire.request("http://sample.com/api/getExpertises", 
               method: .post, parameters: ["Id":2]).responseJSON { 
                 (response) in
            if response.result.isSuccess{

                if let data = response.data{
                    let experts = JSON(data)
                    for i in experts{
                        let id = i.1["id"].string!;
                        let title = i.1["expertise"].string!


             self.categories.append(Category(id:Int(id)!,title: title))
                    }
                    completion(self.categories);
                }
            }
        }

    }
}

,并在ViewController中:

    categories = ServiceModel.shared.getcategories(completion: { 
 //in this line i get error 
        (Categories) in
        print(Categories)
    })

1 个答案:

答案 0 :(得分:1)

错误表明getcategories的返回值为(),无法将其分配给类型为categories的数组Category,因此内部ViewController应该是喜欢

var categories = [Category]()

ServiceModel.shared.getcategories { res in
    print(res) 
    self.categories = res
    // or 
    print(ServiceModel.shared.categories)
}