我正在使用日期组件来获取用户的年龄,但出现错误。 你能告诉我我在这里缺少什么吗?
var calendar = Calendar(identifier: .gregorian)
var components: DateComponents? = calendar.dateComponents([.year, .month, .day], from: datePicker.date, to: Date)
我收到此错误消息:
Type of expression is ambiguous without more context
这里提出了类似的问题:
how to resolve “Type of expression in ambiguous without more context”? in swift 3.0
但它对我不起作用。
最佳答案
函数的参数应该是类的实例而不是类名:
var components: DateComponents? = calendar.dateComponents([.year, .month, .day], from: datePicker.date, to: Date())
如果我们引用这个函数的库定义:
public func dateComponents(_ components: Set, from start: Date, to end: Date) -> DateComponents
Date
是要传递给此函数的参数的类型。计算用户的年龄是计算其生日(datePicker.date
,它是 Date
的实例)和现在(Date ()
,它也是一个实例(如果Date
)。
关于swift - 日期组件出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876918/