Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not cast value of type 'Swift.UInt32' to 'Swift.Int'

In Tests project I've got extensions with some test helper functions. Like this:

extension Employee {
    static func mockDict() -> Dictionary<String, Any>! {
        return ["ID": arc4random() % 1000,
                "FirstName": "Employee First Name",
                ...]
    }
}

(I've stripped unnecessary code). I've got problem accessing ID from this dictionary for some yet unknown reason. I've got SIGABRT 6 when casting

employeeDict["ID"] as! Int

Xcode debugger console also don't like this particular integer:

Ints

Strings work fine. Have you encountered such problem? Any ideas?

EDIT: Just in case anyone will encounter this problem too. CASTING FROM UInt32/Int32 TO Int FAILS BY DESIGN. Even if object was casted into Any or Anyobject inbetween. Even though

@available(*, message: "Converting UInt32 to Int will always succeed.")
public init?(exactly value: UInt32)

in Int's declaration

public struct Int : SignedInteger, Comparable, Equatable {
    ...
}

and

public struct Int32 : SignedInteger, Comparable, Equatable {
    ...
}

EDIT 2 for those who might encounter this behaviour in JSON serialization. Yes, serialization fails with error NSInvalidArgumentException Invalid type in JSON write (_SwiftValue) if asked to serialize UInt32, Int64 or any Integer protocol instance other than Int

like image 222
user1232690 Avatar asked Dec 15 '22 02:12

user1232690


2 Answers

Try this:

let a = employeeDict["ID"] as! UInt32
let number = Int(a)

Now you can use number to perform any action.

like image 154
Pranav Wadhwa Avatar answered Mar 15 '23 22:03

Pranav Wadhwa


This works for me:

Int("\(employeeDict["ID"]!)")
like image 41
Oz Shabat Avatar answered Mar 15 '23 23:03

Oz Shabat