I declared a CoreData entity Address with a 'zip' attribute of type Int16.
Problem is, when I assign an integer to that attribute:
address?.zip = Int(zipField.text!)
I get an error saying Cannot assign value of type Int to type Int16. Makes sense (I guess).
Problem is, when I try casting that int to an Int16, XCode still blows up on me:
let zip:Int? = Int(zipField.text!)
if zip != nil {
let zip16 = Int16(zip!)
}
It's that line where I convert the integer that causes XCode to crash. I am not really seeing any information in the error message, so I'm not sure what to try.
In general, should I be using Int64 because of the operating system of these phones?
You should banish all !
s from your code. That just tells the compiler "crash here if I do something wrong":
if let str = zipField.text,
let zip = Int16(str) {
address?.zip = zip
}
Also, you should read about Swift's guard
statement because there's no point in running any of that code if you don't have an address. Something like:
guard let addr = address else { return }
addr.zip = 90210
You can use:
address?.zip = Int16(zipField.text!)
And in document of structure Int16
, about init?(String, radix: Int)
,there is the following discussion:
If text does not match the regular expression “[+-]?[0-9a-zA-Z]+”, or the value it denotes in the given radix is not representable, the result is nil.
So you should make sure the text is valid in order to convert.
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