Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Int with Swift

The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers.

@IBOutlet var txtBox1 : UITextField @IBOutlet var txtBox2 : UITextField @IBOutlet var txtBox3 : UITextField @IBOutlet var lblAnswer : UILabel   @IBAction func btn1(sender : AnyObject) {      let answer1 = "The acceleration is"     var answer2 = txtBox1     var answer3 = txtBox2     var answer4 = txtBox3 
like image 402
Marwan Qasem Avatar asked Jun 09 '14 06:06

Marwan Qasem


People also ask

How do I cast an int in Swift?

swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.

How do I check if a string is int Swift?

Swift – Check if Variable/Object is Int To check if a variable or object is an Int, use is operator as shown in the following expression. where x is a variable/object. The above expression returns a boolean value: true if the variable is an Int, or false if not an Int.


1 Answers

Updated answer for Swift 2.0+:

toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String:

let a: Int? = Int(firstTextField.text) let b: Int? = Int(secondTextField.text) 
like image 119
Paraneetharan Saravanaperumal Avatar answered Sep 21 '22 07:09

Paraneetharan Saravanaperumal