Reputation: 322
I'm making an app, specifically a tip calculator, to practice my Swift skills. Currently using Swift 5.
I've set up the layout, labels, textfields, etc. But one problem I am running into is the optional string from the user input in text field box. I am trying to multiply the user input (String?) with the slider value, which is a Float.
I've tried several ways, force unwrapping, guard statements, if let, and type casting, but everything I get something similar where Xcode won't let me mix two types together. I've also gotten the text field input to an optional Float (Float?) but still, Xcode wants me to find a way to get the two types together.
My text field input box is a variable closure.
private let priceTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "$00.00"
textField.textColor = UIColor.black
textField.font = UIFont.init(name: "HelveticaNeue-Thin", size: 60)
textField.keyboardType = UIKeyboardType.numberPad
textField.textAlignment = .center
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.borderStyle = UITextField.BorderStyle.none
textField.sizeToFit()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
This is my slider action function that will calculate the tip amount.
@objc func sliderChange() {
totalTipAmount.text = (tipSlider.value) * Float(priceTextField.text! as NSString)
myTipTextView.text = "My Tip (\(Int(tipSlider.value.rounded()))%):"
}
Upvotes: 2
Views: 1236
Reputation: 15258
Your calculation seems fine but it might be throwing a compiler error for setting Float
in place of String
to totalTipAmount
. You can try as follows,
@objc func sliderChange() {
guard let priceText = self.priceTextField.text, let price = Float(priceText) else { return }
totalTipAmount.text = "\(tipSlider.value * price)"
}
Upvotes: 2