Check if input countains numbers in 2 fields in xcode - ios

So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}

You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}

Related

How to check if a user inputed answer has letters, and if so, how would you just default that answer into a 0?

Heres the code I have so far, now when a user inputs any letter, my label display nothing, what I would like to figure out is how to turn that nothing "", into a 0. I tried doing an if statement on my "label.txt ="'s but that didn't pan out. What would be a better way of finding my desired results?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let positiveArray = gameResultsArray.filter {
(item: Int) -> Bool in return item > 0
}
var avgArrayValue = 0
if positiveArray.count == 0
{
avgArrayValue = 0
}else {
avgArrayValue = sumArray / positiveArray.count
}
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:
Instead of this:
guard let game1Results = Int(text1) else { return }
Use this:
let game1Results = Int(text1) ?? 0

How to find the average of just the user inputs above 0

so I'm trying to find the average of my results using only user inputed values above 0. I'm not sure how I would check the results in the array to find out which values are above 0 and exclude them from the calculation in swift.
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let avgArrayValue = sumArray / gameResultsArray.count
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
To filter out all values above 0 in an array, use the filter method. This will return a subset of your original array with all values passing the condition declared inside -
var demoArray = [-1, -8, 0, 1, 5 ,6]
var positiveArray = demoArray.filter { (item: Int) -> Bool in
return item > 0
}
print(positiveArray) // [1, 5, 6]
simply you can use filter
..
let sumArray = gameResultsArray.filter({$0 > 0})
let avgArrayValue = sumArray.reduce(0, +) / sumArray.count

Hide keyboard in view after inputting values?

I have a small calculator built into 3 different views. On all the calcuulators, I would like to have the keyboard disappear upon either tapping anywhere on the screen or upon pressing the button to calucate a value. Ive researched several sources and have become confused on how to implement any code for this. My calculator code is below. Thanks in advance!
class Calculators: UIViewController {
#IBOutlet var fluidIn: UITextField!
#IBOutlet var timeIn: UITextField!
#IBOutlet var dripIn: UITextField!
#IBOutlet var dripResult: UILabel!
#IBOutlet var weight: UITextField!
#IBOutlet var etomidate: UILabel!
#IBOutlet var succ: UILabel!
#IBOutlet var roc: UILabel!
#IBOutlet var ketamine: UILabel!
#IBOutlet var lbsIn: UITextField!
#IBOutlet var KgIn: UITextField!
#IBOutlet var KgOut: UILabel!
#IBOutlet var LbsOut: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func calculate(sender: UIButton) {
let Number2 = Double(weight.text!)
let etommult = (0.3)
let etomresult = Number2! * etommult
etomidate.text = "\(etomresult)"
etomidate.text = NSString(format:"%2.1f mg",etomresult)as String;
let Number3 = Double(weight.text!)
let succmult = (2.0)
let succresult = Number3! * succmult
succ.text = "\(succresult)"
succ.text = NSString(format: "%2.1f mg",succresult)as String;
let Number4 = Double(weight.text!)
let rocmult = (1.0)
let rocresult = Number4! * rocmult
roc.text = "\(rocresult)"
roc.text = NSString(format: "%2.1f mg",rocresult)as String;
let Number5 = Double(weight.text!)
let fentmult = (2.0)
let fentresult = Number5! * fentmult
ketamine.text = "\(fentresult)"
ketamine.text = NSString(format: "%2.1f mg",fentresult)as String;
}
#IBAction func KgConv(_ sender: Any) {
let kg = Double(lbsIn.text!)
let kgmult = (2.2)
let kgresult = kg! / kgmult
KgOut.text = "\(kgresult)"
KgOut.text = NSString(format: "%2.1f kg",kgresult)as String;
}
#IBAction func LbsConv(_ sender: Any) {
let lbs = Double(KgIn.text!)
let lbsmult = (2.2)
let lbsresult = lbs! * lbsmult
LbsOut.text = "\(lbsresult)"
LbsOut.text = NSString(format: "%2.1f kg",lbsresult)as String;
}
#IBAction func dripCalc(_ sender: Any) {
let cc = Double(fluidIn.text!)
let min = Double(timeIn.text!)
let fct = Double(dripIn.text!)
let dripRes = (cc! * fct!) / min!
dripResult.text = "\(dripRes)"
dripResult.text = NSString(format: "%2.1f gtts/min",dripRes)as String;
}
Call the below code whenever and wherever you want to hide the keyboard in viewController.
view.endEditing(true)

How To Fix: "Expression is Ambiguous".

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!!
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"
}
}
}
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)")
}
}

Converting string value from text field to integer

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!
}
}
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
}

Resources