[英]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.