Reputation: 11
I am trying to create an app that can help you calculate sales tax on an item. Of course the app requires multiplication But I keep encountering the error:
"Type of expression is ambiguous without more context"
Can you help me? I'm new to swift so also try to explain why I am incorrect. This is my code so far:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Item: UITextField!
@IBOutlet weak var Tax: UITextField!
@IBOutlet weak var Answer: UITextField!
@IBAction func Calculate(_ sender: Any) {
let a = Item.text
let conversionRate = Tax
let b = Int(a!)! * conversionRate
Answer.text = ("\(b)")
}
}
Thanks!!
Upvotes: 0
Views: 104
Reputation: 2044
You're trying to multiply a variable of UITextField type with a variable of Int. Try this:
class ViewController: UIViewController {
@IBOutlet weak var Item: UITextField!
@IBOutlet weak var Tax: UITextField!
@IBOutlet weak var Answer: UITextField!
@IBAction func Calculate(_ sender: Any) {
guard let a = Int(Item.text ?? "0") else { return }
guard let conversionRate = Int(Tax.text ?? "0") else { return }
let b = a * conversionRate
Answer.text = ("\(b)")
}
}
Upvotes: 0
Reputation: 318934
Your primary issue is your attempt to multiply an Int
and a UITextField
.
You attempt to create an Int
from Item.text
but you make no similar attempt to convert Tax.text
to a number.
There are also many other issues with your code. You are using the !
operator too much and your app will crash as a result.
And your naming conventions need to be improved. Variables and methods should start with lowercase letters.
Here's your code as it should be written:
class ViewController: UIViewController {
@IBOutlet weak var item: UITextField!
@IBOutlet weak var tax: UITextField!
@IBOutlet weak var answer: UITextField!
@IBAction func calculate(_ sender: Any) {
if let itemStr = item.text, let taxStr = tax.text, let itemVal = Int(itemStr), let taxVal = Int(taxStr) {
let result = itemVal * texVal
answer.text = "\(result)"
} else {
answer.text = "Invalid values"
}
}
}
Upvotes: 1