how to add 2 textfields togethers as int (swift3)

2019-03-07 00:55发布

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!

3条回答
够拽才男人
2楼-- · 2019-03-07 01:16

Try this:

    if let val1 = Int(t3.text!), let val2 = Int(t4.text!)
    {
        let sum = val1 + val2
        print(sum)
    }
查看更多
做个烂人
3楼-- · 2019-03-07 01:19

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)
  }
查看更多
走好不送
4楼-- · 2019-03-07 01:24
let t3Value: Int? = Int(t3.text!)
let t4Value: Int? = Int(t4.text!)
let final = t3Value! + t4Value!
print("Sum \(final)")

Hope this helps!

查看更多
登录 后发表回答