【问题标题】:Getting Error in Date Components在日期组件中出现错误
【发布时间】:2018-08-16 12:19:12
【问题描述】:

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

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

我收到此错误消息:

没有更多上下文的表达类型是模棱两可的

这里提出了类似的问题:

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

但它对我不起作用。

【问题讨论】:

  • 最后一个参数应该是date 而不是Date(这是一种类型)。你可能想要..., to: Date())
  • @MartinR 你能解释一下吗
  • 要获取当前日期,您需要创建一个不带任何参数的Date 实例,这是@MartinR 认为您想要的最后一个参数。所以用Date()代替Date
  • @MartinR 谢谢,成功了

标签: swift datepicker calendar


【解决方案1】:

函数的参数应该是类的实例而不是类名:

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

如果我们参考这个函数的库定义:

public func dateComponents(_ components: Set, from 开始:日期,结束:日期)-> DateComponents

Date 是要传递给此函数的参数的类型。计算用户的年龄是计算其生日(datePicker.date,如果Date 是一个实例)和现在(Date(),如果Date 也是一个实例)的日期差的结果。

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多