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:
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
Try this:
let a = employeeDict["ID"] as! UInt32
let number = Int(a)
Now you can use number
to perform any action.
This works for me:
Int("\(employeeDict["ID"]!)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With