简体   繁体   English

将“JSON”类型的非可选值与“nil”进行比较总是返回 true。 有什么建议可以解决这个问题吗?

[英]Comparing non-optional value of type 'JSON' to 'nil' always returns true. Any suggestion to fix this?

if let vendorId = vendor?.id {
        APIManager.shared.getProducts(vendorId: vendorId, completionHandler: { (json) in

            if json != nil { <<<<<<<<<Comparing non-optional value of type 'JSON' to 'nil' always returns true
                self.products = []
                if let tempProducts = json["products"].array {

                    for item in tempProducts {
                        let product = Product(json: item)
                        self.products.append(product)
                    }

                    self.tableView.reloadData()
                    Helpers.hideActivityIndicator(self.activityIndicator)
                }
            }
        })
    }
}

In My APIManager.swift在我的APIManager.swift

import Foundation
import Alamofire
import SwiftyJSON
import FBSDKLoginKit

class APIManager {

static let shared = APIManager()

let baseURL = NSURL(string: BASE_URL)

var accessToken = ""
var refreshToken = ""
var expired = Date()

// Request Server Function // 请求服务器 Function

func requestServer(method: Alamofire.HTTPMethod , path: String, params: [String: AnyObject]?, encoding: ParameterEncoding, completionHandler: @escaping (JSON?) -> Void ) {

    let url = baseURL?.appendingPathComponent(path)

    refreshTokenIfNeed {
        AF.request(url!, method: method, parameters: params, encoding: encoding, headers: nil).responseJSON{ response in

            switch response.result {
            case .success(let value):
                let jsonData = JSON(value)
                completionHandler(jsonData)
                break

            case .failure:
                completionHandler(nil)
                break
            }
        }
    }

}

// API - Getting the latest order (Customer) // API - 获取最新订单(客户)

 func getLatestOrder(completionHandler: @escaping (JSON) -> Void) {

    let path = "api/customer/order/latest/"
    let params: [String: Any] = [
        "access_token": self.accessToken
    ]
    requestServer(method: .get, path: path, params: params as [String : AnyObject], encoding: URLEncoding()) { (json) in
        print(json!)
    }
}
}

as json is non optional in your case, comparing it with nil will always return true.由于 json 在您的情况下是非可选的,因此将其与nil进行比较将始终返回 true。 You simply cannot compare it with nil.你根本无法将它与 nil 进行比较。 If you expect it to be nil , then it should be optional.如果您希望它为nil ,那么它应该是可选的。 If you are sure that it will never be nil , let it be like it is now, just remove the if condition.如果您确定它永远不会是nil ,让它像现在一样,只需删除 if 条件。 But be aware that if it goes nil during runtime it would cause crash.但请注意,如果它在运行时nil ,则会导致崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 非可选类型可以为零吗? - Can a non-optional type be nil? 不能在“任何”SWIFT类型的非可选值上使用可选链接 - cannot use optional chaining on non-optional value of type 'Any' SWIFT 致命错误:解开可选值时意外发现nil(无法强制解开非可选类型&#39;String&#39;的值) - fatal error: unexpectedly found nil while unwrapping an Optional value (cannot force unwrap value of non-optional type 'String') 不能对“ViewController”类型的非可选值使用可选链接 - Cannot use optional chaining on non-optional value of type 'ViewController' 无法强制解开非可选类型“ XCUIElement”的值 - Can not force unwrap value of non-optional type 'XCUIElement' 无法强制打开非可选类型“ UIImage”的值 - Cannot force unwrap value of non-optional type 'UIImage' 我收到一条警告,将我的OPTIONAL值与not-nil比较会始终返回true - I am getting a warning comparing my OPTIONAL value to not-nil will always return true nil 合并运算符 &#39;??&#39; 的左侧具有非可选类型“字符串”,因此从不使用右侧 - Left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used 可选和非可选不能从返回可选的函数中返回 - Optional and non-optional not able to be returned from function that returns an optional 如何将可选类型绑定到非可选类型 - How to binding a optional type to non-optional type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM