Matteo Collina Matteo Collina - 16 days ago 4
Swift Question

Convert UITextField in Int or Double

I am having issue with this code, learning swift and I cannot understand why.

What I want to do is user enter on two TextField two numbers, click a Button, and then get the result on Label.

I know TextField don't allow Int, but only string and I know there is method to convert string to Int, but it is not working for me.

Here is the code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var firstNumber: UITextField!
@IBOutlet weak var secondNumber: UITextField!
@IBOutlet weak var resultButton: UIButton!
@IBOutlet weak var resultNumber: UILabel!

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.


override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

var firstNumberConv :Int? = Int(firstNumber.text)
var secondNumberConv :Int? = Int(secondNumber.text)
var result = firstNumberConv + secondNumberConv

@IBAction func resultFunction(_ sender: AnyObject) {
resultNumber.text = result




why donĀ“t put your code inside of your action

something like this

@IBAction func resultFunction(_ sender: AnyObject) {
    let firstNumberConv :Int? = Int(firstNumber.text!)
    let secondNumberConv :Int? = Int(secondNumber.text!)
    let result = firstNumberConv! + secondNumberConv!
    resultNumber.text = String(result)


I hope this helps you