web-dev-qa-db-fra.com

Créer une date future dans Swift avec NSDate ()

Je reçois une erreur: "Argument manquant pour le paramètre 'coder' dans l'appel" pour le code suivant:

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

La documentation appelle à:

NSCalendar.currentCalendar().dateByAddingComponents(<#comps: NSDateComponents?#>, toDate: <#NSDate?#>, options: <#NSCalendarOptions#>)

Quelqu'un peut-il voir ce que je manque? Je ne vois pas de paramètre appelé 'codeur' requis.

22
krisacorn

à quoi ça ressemble d'être avec

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

Objectif c

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

Syntaxe pour 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

Dernières Swift 3 syntaxe: 

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

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

J'espère que cela t'aides!

0
Abhishek Jain