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
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 .
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With