web-dev-qa-db-ja.com

Swiftに将来の日付を作成する

次のコードで「呼び出し中のパラメーター '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#>)

誰かが私が欠けているものを見ることができますか? 「コーダー」という名前のパラメーターが必要と表示されません。

23
krisacorn

それがどのように見えるか

Swift 4.x

let date = Date()
var components = DateComponents()
components.setValue(1, for: .month)
let expirationDate = Calendar.current.date(byAdding: components, to: date)

Swift 2.0

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))

Swift 1.2

var components = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(0))

Objective-C

NSDate *date = [NSDate new];  
NSDateComponents *components = [NSDateComponents new];
components.month = 1;
NSDate *expirationDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];
51
holex

Swift 3の構文

var components = DateComponents()
components.setValue(1, forComponent: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date, options: [])
12
Luke Bartolomeo

最新Swift構文:

var components = DateComponents()
components.setValue(1, for: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date)
6
Claus

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)

お役に立てれば!

1
Abhishek Jain