how to add 2 textfields togethers as int (swift3)

无人久伴 提交于 2019-12-02 13:08:17

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)
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!