unsure how to unwrap uilabel optional to calculate my to uilabels - swift

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

Related

How to allow dot or comma in UITextField in calculation?

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)
...

why Xcode didn't make addition?

I use gm stepper in my app and , it corresponding to labels. I have 4 different labels and one additional label for addition to values . The labels which corresponding to GM Steppers working well but ı stumble in addition values of labels.
class ViewController: UIViewController {
#IBAction func gmstp1(_ sender: GMStepper) {
label1.text = String(sender.value*1.5)
label6.text = String(sender.value)
}
#IBOutlet weak var label1: UILabel!
#IBAction func gmstp2(_ sender: GMStepper) {
label2.text = String(sender.value*0.89)
}
#IBOutlet weak var label2: UILabel!
#IBAction func gmstp3(_ sender: GMStepper) {
label3.text = String(sender.value*26)
}
#IBOutlet weak var label3: UILabel!
#IBAction func gmstp4(_ sender: GMStepper) {
label4.text = String(sender.value*4)
}
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
My question about ; Is there any solution without using buttons? Could you handle that?
*Label5 using for summary.
Simply because, unlike a GMStepper, a UILabel doesn't have a value property. So you'll have to get the text string in each label, convert it to a Double, and then add them up:
if let text1 = label1.text, let value1 = Double(text1),
let text2 = label2.text, let value2 = Double(text2),
let text3 = label3.text, let value3 = Double(text3),
let text4 = label4.text, let value4 = Double(text4) {
let sum = value1 + value2 + value3 + value4
label5.text = String(sum)
}

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

How to use UIStepper to put integer in to a text field with swift

How Can I use Swift to put integer in textfield from UIStepper?
this is how I did it in Objective C:
- (IBAction)oneClicker:(UIStepper *)sender {
self.oneValue.text = [NSString stringWithFormat:#"%d",
[[NSNumber numberWithDouble:[(UIStepper *)sender value]] intValue]];
AudioServicesPlaySystemSound(_PlaySound);
}
It's simple
#IBOutlet weak var oneValue: UITextField!
#IBAction func oneClicker(sender: UIStepper) {
self.oneValue.text = Int(sender.value).description
}
Here is how I got it to work don't know if the best way but here it is
#IBOutlet weak var oneClicker: UIStepper!
#IBAction func oneClicker(sender: UIStepper) {
oneValue.text = "\(Int(oneClicker.value))"
}
While trying above, got an error. Tried something different and it worked.
#IBOutlet var quantity: UILabel!
#IBOutlet var StepCounter: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
StepCounter.autorepeat = true
StepCounter.maximumValue = 10.0
StepCounter.minimumValue = 1.0
println(StepCounter.value)
quantity.text = "\(Int(StepCounter.value))"
StepCounter.addTarget(self, action: "stepperValueDidChange:", forControlEvents: .ValueChanged)
}
func stepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UILabel] = [StepCounter: quantity]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}