-2

I'm really new to Swift and I am having problems with the conversion of a string (entered in a text field) to an integer.

I'm trying to create a small calculation app (I was following a tutorial on YouTube but it's old).

My app has 3 text fields, a label (that is meant to display the result), and a button to start the calculation.

Here's the code:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var valueA: UITextField!
    @IBOutlet weak var valueB: UITextField!
    @IBOutlet weak var valueC: UITextField!
    @IBOutlet weak var result: UILabel!

    @IBAction func calculateTotal(_ sender: Any) {
        var a:Int? = Int(valueA.text)
        var b:Int? = Int(valueB.text)
        var c:Int? = Int(valueC.text)
        var answer = a! * b! * c!
    }
}
Krunal
  • 77,632
  • 48
  • 245
  • 261
CW2020
  • 29
  • 1
  • You need to [edit] your question with a clear description of what help you need with the code you posted. – rmaddy Jul 23 '17 at 03:51
  • 1
    Possible duplicate of [Swift - Converting String to Int](https://stackoverflow.com/questions/24115141/swift-converting-string-to-int) – ninjaproger Jul 23 '17 at 04:07
  • What is the error? You should mention that if you need to get any help. – adev Jul 23 '17 at 05:50

1 Answers1

-1

Try this (crash free code and you can add n number of textfield/string values as a number string):

var arrayOfTextFieldValues = [valueA.text, valueB.text, valueC.text]

@IBAction func calculateTotal(_ sender: Any) {
        if let multiplication = multiplication(arrayString: arrayOfTextFieldValues) {
            print("Answer = \(multiplication)")
            result.text = "\(multiplication)"
        }
}


// handle operations
func multiplication(arrayString: [String?]) -> Int? {

    var answer:Int?
    for arrayElement in arrayString {
        if let stringValue = arrayElement, let intValue = Int(stringValue)  {
            answer = (answer ?? 1) * intValue
        }
    }

    return answer
}
Krunal
  • 77,632
  • 48
  • 245
  • 261