Jonnny Jonnny - 1 year ago 85
Swift Question

Swift 3 cast UITexField to Int

I'm receiving a compiler error and i'm not really sure why. I'm sure there is a simple answer for this. I have a core data attribute I'm trying to assign before saving. In my Core Data Property file it's defined as this:

@NSManaged public var age: Int32

I am using a UIPicker to select it and put it into an inputView. That works fine, so
ageTextField: UITextField!
holds the value. As I try to assign this to the CoreData object just before saving I get the following

person.age = ageTextField.text -> Cannot assign String? to Int32.

Ok, I understand that, so I cast it

person.age = Int(ageTextField.text) -> Value of Optional String not unwrapped...

Ok, I get that, so I unwrapped it, it asks to unwrap again and I agree:

person.age = Int(ageTextField.text!)! -> Type of expression is ambiguous without more context

I'm not sure what is wrong here, just looking over some old Swift 2 code of mine and this worked. This is my first code with Swift 3 though.

Answer Source

The immediate issue is the use of the wrong type. Use Int32, not Int. But even once that is fixed, you have lots of other issues.

You should safely unwrap the text and then the attempt to convert the string to an integer.

if let text = ageTextField.text, let num = Int32(text) {
    person.age = num

The use of all of those ! will cause a crash if the text is nil or it contains a value that isn't a valid number. Always use safe unwrapping.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download