-1

I want to set the age limit, when I select the date of birth if the age is less than 18, then I print an error

 @objc func handleDatePicker(sender: UIDatePicker) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MMMM/yyyy"

        dateBirthday.text = dateFormatter.string(from: sender.date)

        if let date = dateFormatter.date(from: dateBirthday.text!) {
            let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year!
            print(age)  //
            self.age.text = "You are \(age) age"
            `continue`.isEnabled = true
        } else {

            let date = dateFormatter.date(from: dateBirthday.text!)
            let age = Calendar.current.dateComponents([.year], from: date!, to: Date()).year!
            print(age)
          if age < 18 {

                self.age.text = "Error you are \(age)"
            }
    }
    }
ozy
  • 21
  • 3
  • What's wrong with your code? You should get the date/age anyway, and then apply the if/else (<18) code. – Larme May 06 '18 at 18:55
  • when the age is less than 18, the error does not come out – ozy May 06 '18 at 18:57
  • Think: You wrote an `if let/else` test. Where does your code? Does it pass the if let? Why should it pass it, or why it shouldn't. Then read the second line of my previous comment. – Larme May 06 '18 at 18:59

2 Answers2

2

You can do it like this:

    if let date = dateFormatter.date(from: dateBirthday.text!) {
        let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year!

        if age >= 18 {
            print(age)
            self.age.text = "You are \(age) age"
            continue.isEnabled = true
        } else {
            self.age.text = "Error you are \(age)"
        }
    }
rbaldwin
  • 4,581
  • 27
  • 38
2

Move your date and age formatter out of your if statements. Usually, if you have the same code in both branches of an if statement it can be pulled before or after the code.

if let date = dateFormatter.date(from: dateBirthday.text!) {
    let age = Calendar.current.dateComponents([.year], from: date!, to: Date()).year!
    print(age)

    if age < 18 {
       self.age.text = "Error you are \(age)"
    } else {
       self.age.text = "You are \(age) age"
       `continue`.isEnabled = true
    }
}
Zyntx
  • 659
  • 6
  • 19