Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift CoreData -- Cannot assign value of type 'Int' to type 'Int16'

Tags:

ios

core-data

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?

like image 699
Daniel Thompson Avatar asked Mar 07 '17 00:03

Daniel Thompson


2 Answers

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
like image 140
Dave Weston Avatar answered Oct 20 '22 00:10

Dave Weston


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.

like image 28
LinShiwei Avatar answered Oct 20 '22 00:10

LinShiwei