我收到一个错误:“在调用中缺少参数'coder'的参数”以获取以下代码:
var components = NSDateComponents()
components.setValue(1,forComponent: NSCalendarUnit.CalendarUnitMonth);
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(),options:0)
文档要求:
NSCalendar.currentCalendar().dateByAddingComponents(<#comps: NSDateComponents?#>, toDate: <#NSDate?#>, options: <#NSCalendarOptions#>)
任何人都能看到我错过的东西吗?我没有看到名为'coder'的参数。
答案 0 :(得分:51)
它与
的关系let date = Date()
var components = DateComponents()
components.setValue(1, for: .month)
let expirationDate = Calendar.current.date(byAdding: components, to: date)
let components: NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.Month);
let date: NSDate = NSDate()
let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))
var components = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(0))
NSDate *date = [NSDate new];
NSDateComponents *components = [NSDateComponents new];
components.month = 1;
NSDate *expirationDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];
答案 1 :(得分:12)
Swift 3的语法
var components = DateComponents()
components.setValue(1, forComponent: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date, options: [])
答案 2 :(得分:6)
最新的 Swift 3 语法:
var components = DateComponents()
components.setValue(1, for: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date)
答案 3 :(得分:1)
Swift 4版本
var components = DateComponents()
components.setValue(1, for: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date, wrappingComponents: false)
希望这有帮助!