无法将类型 'Int64?' 的值转换为预期的参数类型 'Int'

Cannot convert value of type 'Int64?' to expected argument type 'Int'

当我尝试将 job?.id(一个 Int64)作为 Int 参数传递时(虽然我知道它不是那么大),swift 编译器提示此错误,我尝试了几种方法来转换它,但没有成功:

Cannot convert value of type 'Int64?' to expected argument type 'Int'

我的代码:

Job.updateJobStatus(token: tok, jobId: job?.id, status:JobSatus.canceled) { (result, error) in
        if result != nil
        {

        }
        else if error != nil
        {

        }
    }

您有两个问题需要解决。首先,您需要处理 job 是可选的。然后,您需要处理 job.idjobId 参数不同的数据类型。

对于可选问题,您有很多选择:

guard let job = job else { return }

Job.updateJobStatus(token: tok, jobId: Int(job.id), status:JobSatus.canceled) { (result, error) in
    if let result = result {
    } else if let error = error {
    }
}

或者您可以回退到默认值:

Job.updateJobStatus(token: tok, jobId: Int(job?.id ?? 0), status:JobSatus.canceled) { (result, error) in
    if let result = result {
    } else if let error = error {
    }
}

请注意,您真的应该让 jobId 参数与 id 属性 具有相同的数据类型。如果值太大而无法转换,从 Int64Int 的转换可能会失败。

这与

有关

Swift 3 introduces failable initializers to safely convert one integer type to another. By using init?(exactly:) you can pass one type to initialize another, and it returns nil if the initialization fails. The value returned is an optional which must be unwrapped in the usual ways.

Int(exactly: yourInt64)

你可以很容易地去喜欢:

let int64Value: Int64 = 123456
let intValue = NSNumber(value: int64Value).intValue