【问题标题】:Nil is not compatible with expected argument type 'JSON'Nil 与预期的参数类型“JSON”不兼容
【发布时间】:2018-12-23 10:56:18
【问题描述】:

以前它与Swift 3 配合得很好,但是当我切换到Swift 4 时,无法找到类型为JSON(SwiftyJson Library) 的补全问题

static func getRoster(information: [String: String], completion:@escaping ([Player],JSON,Paging?,WSResponse,NSError?) -> Void){
        Alamofire.request(NetWorkingConstants.baseURL+NetWorkingConstants.Team.get_all_roster, method: .post, parameters: information, encoding: JSONEncoding.default, headers:StarsLeagueUser.sharedInstance.getDefaultHeaders()).responseJSON { (response) in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                let wsResponse = WSResponse(code: json["response_code"].stringValue, message: json["message"].stringValue)


                if wsResponse.code == ServerCode.success{
                    print("Success")

                }else if wsResponse.code == ServerCode.unauthorized{
                    print("Session Expire")
                }
            case .failure(let error):

               print("Network Error")
                let wsResponse = WSResponse(code: "1000", message: "Network Error")
                completion([],nil,nil,wsResponse,error as NSError?)//Here is error - Nil is not compatible with expected argument type 'JSON'
                print("GetRoster")
            }
        }
    }

【问题讨论】:

  • 因为您编写的代码期望服务器响应为 json,如果响应不是 json,您将收到错误

标签: json swift completionhandler


【解决方案1】:

更改为 (,JSON?)

func getRoster(information: [String: String], 
 completion:@escaping ([Player],JSON?,Paging?,WSResponse,NSError?) -> Void){

既然能够返回一个 nil 值,那么它应该是可选的

将返回类型 JSON 设为非可选意味着您必须返回一个非可选值,因此返回 nil 是一个问题

var str1:String = nil // error 
var str2:String? = nil // ok  

【讨论】:

  • 谢谢,它的工作,你能解释一下吗?我哪里错了?
【解决方案2】:

如果参数类型是非可选的,则无法传递nil 导致错误发生。将 JSON 声明为可选 (JSON?)。

在您的情况下,我建议使用具有关联类型的枚举作为结果类型。

好处是参数排列得更好,而且你总是有非可选类型,因为你只返回相关参数

enum Result {
   case success([Player], JSON, Paging, WSResponse)
   case failure(WSResponse, Error)
}

然后声明你的方法

func getRoster(information: [String: String], completion:@escaping (Result) -> Void) {

在失败的情况下返回

let wsResponse = WSResponse(code: "1000", message: "Network Error")
completion(.failure(wsResponse, error))

在调用者方法中使用switch

switch result {
    case let .success(players, json, paging, response):
    // handle success
    case let .failure(response, error):
    // handle error
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多