Reputation: 847
I am slowly understanding things in swift, I am coming for a javascript background so it is somewhat familiar.
However variables are urking me.
in JS a variable can be
var varName = 1; //Number
var varName2 = "petey" //String
var conCat = varname + varName2; // 1petey
however in swift String vars and In var are troubling me. All I want to do is capture decimal number from user input from multiple "textField" sources and store that data to variable (which i already have setup) I need to concatinate a few of them with +
then do basic math with the data in the variables with *
and /
.
How do I make the textFeld
only capture?int
or how do I convert text field strings to numbers, e.g. int
?
Upvotes: 0
Views: 11439
Reputation: 1
Use the function in swift inputmethod.intValue();
if any text is entered then it returns with a 0.
Upvotes: 0
Reputation: 2643
The data send from the textField is String. There are multiple ways to convert an Int to a String.
var a:String="\(2+3)" //"5"
And to concatenate a String to Int :
var b:String="Hello "+"\(3*4)" //"Hello 12"
And to Convert a String to an Int from a textField:
var b:Int=textField.text.toInt()
Upvotes: 0
Reputation: 8154
A UITextField
contains a String
, not an Int
, so you have to convert it, e.g.
let number : Int? = textField.text.toInt()
So, there actually is a method to convert from String
to Int
built-in in Swift. Beware, that it returns an optional, because the conversion may fail. So you have to check for nil
before you use the variable.
For your other question, take a look at e.g. UITextField - Allow only numbers and punctuation input/keypad. Basically, you will have to adapt UITextField
and filter it, once there are new entries. On iOS it might be easier, because you can show a numbers-only keyboard.
Upvotes: 1