I am trying to convert 2 textfields to ints and then add them together. I would also like to print the sum in the log.
let jake = t3.text! + t4.text!
Convert text into Int in Swift and an addition like we can do...
//set before this condition Validation for Text field
let sum = (Int(textFirst.text ?? "0")! + Int(textSecond.text ?? "0"))!
print(sum) //Output here
//MARK: - Text Field Delegate Method for Input validation
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
let t3Value: Int? = Int(t3.text!)
let t4Value: Int? = Int(t4.text!)
let final = t3Value! + t4Value!
print("Sum \(final)")
Hope this helps!
Try this:
if let val1 = Int(t3.text!), let val2 = Int(t4.text!)
{
let sum = val1 + val2
print(sum)
}
来源:https://stackoverflow.com/questions/45644141/how-to-add-2-textfields-togethers-as-int-swift3