0

I'm using date component to get user's age but I'm getting error. Can you please tell me what I'm missing here?

var calendar = Calendar(identifier: .gregorian)
var components: DateComponents? = calendar.dateComponents([.year, .month, .day], from: datePicker.date, to: Date)

I'm getting this error message:

Type of expression is ambiguous without more context

Similar question is asked here:

how to resolve “Type of expression in ambiguous without more context”? in swift 3.0

but it did not work for me.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

Parameters of a function should be instances of classes and not class names:

var components: DateComponents? = calendar.dateComponents([.year, .month, .day], from: datePicker.date, to: Date())

If we refer to the library definition of this function:

public func dateComponents(_ components: Set, from start: Date, to end: Date) -> DateComponents

Date is the type of the argument to be passed to this function. Calculating the age of a user is the result of calculating the date difference from their birthday (datePicker.date, which is an instance if Date) and now (Date(), which is also an instance if Date).

ielyamani
  • 17,807
  • 10
  • 55
  • 90