Sum of 3 UITextField? [closed]

2020-04-01 08:05发布

https://ibb.co/nH38wG

Why the result is 123 and not 6 ?

Anyone is able to elaborate and explain it to me please?

2条回答
▲ chillily
2楼-- · 2020-04-01 08:39

You are adding the text (String) values to each other in the label text. You should do this instead:

guard let num1 = Int(textField1.text),
    let num2 = Int(textField2.text),
    let num3 = Int(textField3.text) else {
    return
}

let sum = num1 + num2 + num3
label.text = str+sum
查看更多
叛逆
3楼-- · 2020-04-01 08:57

You are "summing" strings. "1"+"2"+"3"="123". Convert it to a number: Int("1")+Int("2")+Int("3")=6.

label.text = str + Int(textField1.text!)! + Int(textField2.text!)! + Int(textField3.text!)!
查看更多
登录 后发表回答