change user input text to Int for computation

I am using Xcode12 and want to create a label or textfield that would accept and Int or Double. This does not seem possible, so is there a simple way to the the program to take the text from the user input and change it to an Int or Double? The number would then be used in a calculation function.

I a very new to coding so please explain as if you are explaining to someone who understands nothing. Thanks for any help you can give.

When you have a String, you convert to num with:

Code Block
let str = "12"
let num = Int(str) ?? 0
or
Code Block
let numDouble = Double(str) ?? 0.0

So, in your case, you have to get the text of the label with myLabel.text and then convert.

Important to note that Int() or Double() can fail: if you pass "Hello" instead of "12", this cannot be converted to Int (or Double). Hence you get a nil value.
So, result of Int() is an optional.

You could unwrap with
Code Block
let num = Int(str)!

but that is very risky: app will crash if your text is not an Int.
So you can use the ?? (nil coalescing operator):
  • if result is nil, then you give the value after ??

  • otherwise you unwrap (safely) and get an Int or Double (and not an optional).

Don't hesitate to ask if something is not clear.
Otherwise, don't forget to close the thread by marking the correct answer.
Did it work ?

If so, don't forget to close the thread by marking the correct answer.
Otherwise, please explain what doesn't work.
change user input text to Int for computation
 
 
Q