swift - 日期组件出错

标签 swift datepicker calendar

我正在使用日期组件来获取用户的年龄,但出现错误。 你能告诉我我在这里缺少什么吗?

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/

相关文章:

ios - 什么时候使用 Semaphore 而不是 Dispatch Group?

ios - 无法将类型 'MyAppName.ProfileController' 的值转换为 'MyAppName.SelectController'

ios - 使用 UIDocumentPickerController 导入目录

ios - 如何将我的 iOS/Swift 项目转换为可以使用实时 View 的状态?

java - 将时间从 UTC 转换回指定的时区

Java:为什么 Calendral.setTimeInMillis(0) 设置错误的时间

javascript - 没有输入的 jQuery 日期选择器

javascript - jQuery : Increase the size of datepicker widget

javascript - 如何将日期选择器插入 MS Excel 单元格

c# - telerik RadDatePicker 是否支持回历