Reputation: 1
I am using Swift and I want to know how I can store user input as a variable (it’s a double).
I'm still in the learning states so I have been watching youtube tutorials on the situation but nothing helped.
My code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userInput: UITextField!
override func viewDidLoad() {
userInput.delegate = self
}
@IBAction func Increment(_ sender: UIButton) {
var inc = 0
userInput = userInput + inc
}
@IBAction func Decrement(_ sender: UIButton) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
userInput.resignFirstResponder()
}
}
extension ViewController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
The user will be able to enter a number and increment or decrement the number by a certain input value.
Upvotes: 0
Views: 1334
Reputation: 410
//fetch any number from textfield
func getValueFromTextfield() -> Double?{
guard let text = userInput.text else {
print("Missing user input")
return nil
}
guard let doubleValue = Double(text) else {
print("parse failure")
return nil
}
return doubleValue
}
// Now for increment and decrement we have methods be like, Am assuming certain input value as 1
to be used for increment and decrement replace this if needed
func increment(){
// get value
if let value = getValueFromTextfield(){
userInput.text = “\(value + 1)” // increment by 1
}
}
func decrement(){
// get value and check if it’s greater than zero
if let value = getValueFromTextfield(), value > 0{
userInput.text = “\(value - 1)” // decrement by 1
}
}
@IBAction func Increment(_ sender: UIButton) {
increment()
}
@IBAction func Decrement(_ sender: UIButton) {
decrement()
}
These method will help you achieve increment or decrement operation without need to store value in any variable.
If you still want to save value in variable just simply store value returned from method let valueToStore = getValueFromTextfield()
Upvotes: 2
Reputation: 131
@IBAction func Increment(_ sender: UIButton) {
var inc = 0
userInput.text = ( Double(userInput.text) + Double(inc) ).rounded(toPlaces: 1)
}
Upvotes: 0
Reputation: 166
@IBAction func Increment(_ sender: UIButton) {
if let text = userInput.text, var doubleText = Double(text) {
doubleText = doubleText + 1
userInput.text = "\(doubleText)"
}
}
Similarly you can write for Decrement.
Upvotes: 0
Reputation: 27211
Your code won't compile correctly but the answer to your question is:
let doubleValue = Double(userInput.text!)!
converts your code to double
or better using optional unwrapping:
guard let text = userInput.text else {
print("text of userInput is nil")
return
}
guard let doubleValue = Double(text) else {
print("Impossible to parse \(text) into Double")
return
}
print(doubleValue)
Upvotes: 1