How to allow dot or comma in UITextField in calculation? - swift

I am newbie in coding. I just started to learn #swift and trying yo make a calculation app. My problem is my UITextField doesn't work with dot or comma.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var ilkLabel: UITextField!
#IBOutlet weak var ikinciLabel: UITextField!
#IBOutlet weak var sonucLabel: UILabel!
#IBOutlet weak var ilk2Label: UITextField!
#IBOutlet weak var ikinci2Label: UITextField!
#IBOutlet weak var sonuc2Label: UILabel!
#IBOutlet weak var ilk3Label: UITextField!
#IBOutlet weak var ikinci3Label: UITextField!
#IBOutlet weak var sonuc3Label: UILabel!
var sonuc:Double = 0
var sonuc2:Double = 0
var sonuc3:Double = 0
var deneme:Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#IBAction func plusBtn(_ sender: Any) {
func forTrailingZero(temp: Double) -> String {
let tempVar = String(format: "%g", temp)
return tempVar
}
deneme = Double(Int(ikinciLabel.text!)! + 100 / 100 * Int(ilkLabel.text!)!)
sonucLabel.text = String(forTrailingZero(temp: Double(ikinciLabel.text!)! / 14.56 ) )
}
#IBAction func plus2Btn(_ sender: Any) {
}
#IBAction func plus3Btn(_ sender: Any) {
}
}
I expect to make calculation like 1.4 + 2.35 but when i try the app crashes. I can only calculate whole number like 2 + 2.

#matt is right. If the text in ikinciLabel is not an Int, the app crashes. You tell it to crash by using the force unwrap operator: !.
In general
You should only force-unwrap things when you are absolutely sure that the thing you want to unwrap is not nill. In all other cases you should if-let or guard-let the optional, use the nil-coalescing operator (??) (or other ways to unwrap optionals) and handle the nil-case.
In your case
if you want to allow the user to enter floating point numbers using either a comma or a dot, you could simply replace every comma with a dot like so:
let enteredTextWithoutComma = textField.text?.replacingOccurrences(of: ",", with: ".")
This new constant is an optional. To safely make a Double out of it, do:
guard let enteredTextWithoutCommaUnwraped = enteredTextWithoutComma,
let enteredNumber = Double(enteredTextWithoutCommaUnwraped) else {
// one of the two actions didn't work. Maybe the entered phrase was not a number
// do something
return
}
// here you can use the variable enteredNumber. It is now a Double (not an Optional)
...

Related

unsure how to unwrap uilabel optional to calculate my to uilabels

I am new in the developer world and have been on and off since february with swift and Xcode. I am hoping someone could help me out. Im trying to make a simple tip calculator and can't seem to * two uilabels together. this is what i have so far... at the total.text = "(totalAmount) * (tipPercent)" ... thanks any help would be great. :)
#IBOutlet weak var totalAmount: UILabel!
#IBOutlet weak var textFIeld: UITextField!
#IBOutlet weak var tipPercent: UILabel!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var total: UILabel!
#IBOutlet weak var tip: UILabel!
#IBAction func sliderChanged(_ sender: UISlider) {
sldr()
total.text = "\(totalAmount) * \(tipPercent)"
}
#IBAction func buttonPressed(_ sender: Any) {
ttl()
}
func ttl() {
if let grandTotal = textFIeld.text {
totalAmount.text! = "\(grandTotal)"
}
}
func sldr() {
tipPercent.text! = "\(Int(slider.value))"
}
The below expression will just only return you a string without any multiplication that you are expecting.
total.text = "\(totalAmount) * \(tipPercent)"
You know how to unwrap the text as you have done in ttl. You should use the same approach here
if let totalTxt = totalAmount.text, let percentTxt = tipPercent.text {
//Then change to whatever scalar type you want
if let totalAmount = Float(totalTxt), let percent = Float(percentTxt) {
let totalBill = totalAmount * percent
total.text = "\(totalBill)"
}
}

Cannot convert value of type 'String?' to type 'NSString' in coercion

Im trying to make this calculator for various math formulas and I'm stuck at this point. I was following this tutorial
Here's my code:
import UIKit
class pythagorasViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var bLabel: UILabel!
#IBOutlet weak var aField: UITextField!
#IBOutlet weak var bField: UITextField!
#IBOutlet weak var answerLabel: UILabel!
#IBAction func calculateButton(_ sender: UIButton) {
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
var answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The part where I'm getting the error is at:
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
Prefer let to var when possible. You do not need to use NSString. You can cast String to Float?. You need to unwrap both the text property which is a String? (if you have a question about the type of a variable option click and it will show you) and the Float? conversion:
func calculateButton(_ sender: UIButton) {
guard let aText = aField.text,
let bText = bField.text,
let a = Float(aText),
let b = Float(bText) else {
return
}
let answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}

Swift: Cannot subscript a value of type 'Array'

I have just started learning swift ios development. I am encountering this problem which I am not able to solve. Can someone please tell what I am doing wrong? The image below contains screenshot of the error.
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var dayPicker: UIPickerView!
#IBOutlet weak var addButton: UIButton!
#IBOutlet weak var textField: UITextField!
let days = ["Sunday","Monday","Tuesday","Thursday","Friday","Saturday"]
// creates an array of 7 empty arrays
var tableData:Array = [[String]] (count: 7,repeatedValue:[])
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.
}
#IBAction func addObjectToTable(sender: AnyObject) {
if(textField.text != "")
{
print (days[dayPicker.selectedRowInComponent(0)])
print (textField.text!)
tableData[dayPicker.selectedRowInComponent(0)].append(textField.text!); // Error: Cannot subscript a value of type 'Array'
textField.text = ""
tableView.reloadData()
}
}
}
Thanks!
I just remembered I ran into this problem a few times when I went back to some old projects that were a bit outdated. For me the fix was simply to change, in your example,
var tableData:Array = [[String]]
to
var tableData = [[String]]
If you are sure that the tableview will contain only days try to typecast the objects Array of AnyObject to Array of String. then use it.
var day= self.objects![indexPath.row] as! String

Bug when running app "unexpectedly found nil while unwrapping an Optional value"

I have a completed code for a small app I am made and are now stuck on
unexpectedly found nil while unwrapping an Optional value
Anyone have the time to help me by looking over the code and see what to do when it comes to fixing it. I am a rookie when it comes to programming.
Here is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var panelWidthTextField: UITextField!
#IBOutlet weak var panelHightTextField: UITextField!
#IBOutlet weak var panelsWideTextField: UITextField!
#IBOutlet weak var panelsHightTextField: UITextField!
#IBOutlet weak var panelPitchTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultWithLabel: UILabel!
#IBOutlet weak var resultHightLabel: UILabel!
// Removes keyboard when touch outside edit field.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
// Disable button when there is no value in all fields
func textFieldDidEndEditing(textField: UITextField) {
if ((panelWidthTextField.text?.isEmpty != nil) &&
(panelsWideTextField.text?.isEmpty != nil) &&
(panelHightTextField.text?.isEmpty != nil) &&
(panelPitchTextField.text?.isEmpty != nil))
{
self.calculateButton.enabled = true
} else {
self.calculateButton.enabled = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
panelWidthTextField.delegate = self
panelsWideTextField.delegate = self
panelHightTextField.delegate = self
panelsHightTextField.delegate = self
panelPitchTextField.delegate = self
}
// Sends calculation to resolution Display
func calculatePressButton(sender: AnyObject) {
let w = Double(panelWidthTextField.text!)
let sw = Double(panelsWideTextField.text!)
let pi = Double(panelPitchTextField.text!)
let sizew = SizeWidthModel(pw:w!,psw:sw!,ptc:pi!)
resultWithLabel.text=String(sizew.width())
let h = Double(panelHightTextField.text!)
let sh = Double(panelsHightTextField.text!)
let sizeh = SizeHightModel(ph:h!,psh:sh!,ptc:pi!)
resultHightLabel.text=String(sizeh.hight())
}
}
Error that comes up
I am trying do disable the one button I have until all fields are filled in.
Latest error after some fixing
Latest error
Make sure all your IBOutlest are connected with Storyboard. You can identify these connections through little circle with selected dot (Refer the attached image). Or you can print each UITextField and check the nil exception is occurred ?.
override func viewDidLoad() {
super.viewDidLoad()
print(panelWidthTextField.text)
print(panelsHightTextField.text) // I missed to connect outlet so it will throw nil

Swift - Multiply values from two UITextFeild's

I'm trying to calculate two values from two UITextFields. What I did was made the answerScreen equal to the valueOne which I turned into an Int and valueTwo which is supposed to be the opposite of an var with the !. Can somebody tell me what I'm doing wrong?
import UIKit
class ViewController: UIViewController {
// The answer will be here
#IBOutlet weak var answerScreen: UILabel!
// The first number
#IBOutlet weak var valueOne: UITextField!
// The second number
#IBOutlet weak var valueTwo: UITextField!
// The equals button
#IBAction func calculateValues(sender: AnyObject) {
answerScreen.text = valueOne.text.toInt() * valueTwo!
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
let result = (valueOne.text.toInt() ?? 0) * (valueTwo.text.toInt() ?? 0)
answerScreen.text = "\(result)"
Will convert the text field values to Int or use 0 if the conversion failed.
One Can try
var temp = (firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue
For setting value to UILabel
self.resultLable.text = String("\((firstTextField.text! as NSString).integerValue * (secondTextField.text! as NSString).integerValue)")