I have a picker view of int in my Swift code. It has numbers 1-7 in an array called numbers. When I ask to print numbers[row]
inside the didSelectRow
function it prints the correct numbers. But within my submit tapped function it only prints 0. It did this in viewWillAppear
as well.
I essentially want the row to be a variable that I can use as an int to delay some code.
let numbers = [1,2,3,4,5,6,7]
var days = Int()
override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.delegate = self
self.pickerView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
print(days)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(numbers[row])
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return numbers.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var days = numbers[row]
print(days)
}
@IBAction func submitTapped(_ sender: Any) {
databaseRef.child("numbers").child(self.TextField.text!).setValue(["thename" : UserDefaults.standard.value(forKey: "nametext")])
print(days)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(days) , execute: {
databaseRef.child("numbers/\(self.TextField.text!)").removeValue()
})
Does anyone know why it is always returning zero in the submit tapped function?
You're initializing
days
using theInt()
constructor, which is always0
. Thus, in yourviewWillAppear(_:)
method later,0
is printed out, because that's whatdays
was initialized to be. However, in yourpickerView(_:didSelectRow:inComponent:)
method, you're using thevar
keyword to create a new variable calleddays
that is local to thepickerView(_:didSelectRow:inComponent:)
method, and the globaldays
variable is never changed, and is always equal to0
. Therefore, later on in yoursubmitTapped(_:)
method, the globaldays
is still0
.I'm going to assume you want to set the global
days
variable in yourpickerView(_:didSelectRow:inComponent:)
method tonumbers[row]
. To do so, you must remove thevar
keyword next todays
inside thepickerView(_:didSelectRow:inComponent:)
. Inside that method, you can reference it either asdays
orself.days
, as long as you don't use thevar
orlet
keyword to redeclaredays
inside that method