您收到一条错误消息,因为0
它不是的有效值NSCalendarOptions
。对于“无选项”,请使用NSCalendarOptions(0)
或简单地nil
:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: Now,
options: nil)
let age = ageComponents.year
(指定nil
是可能的,因为它NSCalendarOptions
符合RawOptionSetType
从继承的协议NilLiteralConvertible
。)
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: Now,
options: [])
假设使用Swift 3类型Date
和Calendar
:
let Now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: Now)
let age = ageComponents.year!