5

When I try to pass job?.id (an Int64) as Int parameter ( while I know it's not that big ), swift compiler prompts with this error, I tried a couple of ways to cast it, but had no success :

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

My code :

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

        }
        else if error != nil
        {

        }
    }
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210

3 Answers3

8

You can easily go like:

let int64Value: Int64 = 123456
let intValue = NSNumber(value: int64Value).intValue
alitosuner
  • 984
  • 1
  • 10
  • 15
3

This is related to https://stackoverflow.com/a/32793656/8236481

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)
Oxthor
  • 512
  • 4
  • 15
0

You have two issues to solve. First you need to deal with job being optional. Then you need to deal with job.id being a different data type than the jobId parameter.

You have lots of options for the optional issue:

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 {
    }
}

Or you can fallback to a default value:

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

Please note that you really should just make the jobId parameter have the same data type as the id property. The conversion from Int64 to Int can fail if the value is too large to be converted.

rmaddy
  • 314,917
  • 42
  • 532
  • 579