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
Related
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)"
}
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
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)
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
}
This is the code I have. Basically when the user first chooses the quality of the dinning whether it is fine (20%), casual (15%), or a bar (11%). From there the user will then be asked on a 1-5 scale about the food quality, service, etc. Depending what number they choose, for example if the fine dinning was a 5/5 then it will ad 4% to the already 20 percent (each number will have a selected value to add to the tip). Can anyone figure out what's going on? Or if there is a better way about doing it.
import UIKit
#IBDesignable
class ViewController: UIViewController {
#IBOutlet weak var billTotal: UITextField!
var diningValue: Double = 0.0
#IBAction func toggleFineDining(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.20
}
}
#IBAction func toggleCasualDining(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.15
}
}
#IBAction func toggleBartender(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.11
}
}
#IBOutlet weak var service: UITextField!
#IBOutlet weak var friendliness: UITextField!
#IBOutlet weak var foodQuality: UITextField!
#IBOutlet weak var atmosphere: UITextField!
#IBOutlet weak var overall: UITextField!
#IBOutlet weak var recommend: UISwitch!
#IBOutlet weak var total: UILabel!
func totalBill(inputArray: [Double], value: Double, recommend: Bool)->Double{
var array: [Double] = []
let total = inputArray[0]
for var i = 1; i < inputArray.count; ++i {
array.append(inputArray[i] * 0.01)
}
let sum = array.reduce(0, combine: +)
var totalTip = Double()
if recommend == true{
totalTip = sum + value
} else {
if sum < 0.15 {
totalTip = 0.15
} else {
totalTip = sum + value
}
}
let tipValue = totalTip * total
return total + tipValue
}
#IBAction func calcTotal(sender: AnyObject) {
var valueList = [String(service.text), String(friendliness.text), String(foodQuality.text), String(atmosphere.text), String(overall.text)]
let list = doubleArray(valueList)
print(list)
let initialTotal = Double(billTotal.text!)
let total_bill = totalBill(list, value: diningValue, recommend: recommend.selected)
print("Total: ", total_bill)
print(String(format: "%.3f", Double(total_bill)))
total.text = "$" + String(format: "%.2f", Double(total_bill))
//diningValue = diningValue
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0...list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
Your issue is in the last function:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0...list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
Your loop is looping from 0 to list.count and it crashes at list[element] when element is list.count (Out of Index)
You need to change from 0...list.count to 0..<list.count:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0..<list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
I would recommend you to do it in swifty way:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in list {
doubledList.append(Double(element) ?? 0.0)
}
return doubledList
}
A shorter version using map function:
func doubleArray(list: [String])->[Double]{
return list.map( { Double($0) ?? 0.0 })
}