The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the value
This works for me
var a:Int? = Int(userInput.text!)
//Xcode 8.1 and swift 3.0
We can also handle it by Optional Binding, Simply
let occur = "10"
if let occ = Int(occur) {
print("By optional binding :", occ*2) // 20
}
In Swift 4.2 and Xcode 10.1
let string:String = "789"
let intValue:Int = Int(string)!
print(intValue)
let integerValue:Int = 789
let stringValue:String = String(integerValue)
//OR
//let stringValue:String = "\(integerValue)"
print(stringValue)
i have made a simple program, where you have 2 txt field you take input form the user and add them to make it simpler to understand please find the code below.
@IBOutlet weak var result: UILabel!
@IBOutlet weak var one: UITextField!
@IBOutlet weak var two: UITextField!
@IBAction func add(sender: AnyObject) {
let count = Int(one.text!)
let cal = Int(two.text!)
let sum = count! + cal!
result.text = "Sum is \(sum)"
}
hope this helps.
Latest swift3 this code is simply to convert string to int
let myString = "556"
let myInt = Int(myString)
@IBAction func calculateAclr(_ sender: Any) {
if let addition = addition(arrayString: [txtBox1.text, txtBox2.text, txtBox3.text]) {
print("Answer = \(addition)")
lblAnswer.text = "\(addition)"
}
}
func addition(arrayString: [Any?]) -> Int? {
var answer:Int?
for arrayElement in arrayString {
if let stringValue = arrayElement, let intValue = Int(stringValue) {
answer = (answer ?? 0) + intValue
}
}
return answer
}