2017-01-11 15 views
1

スウィフトを使用して、過去50年間のすべての日曜日の日付を探したい。私は 'enumerateDates'(カレンダーのインスタンスメソッド)が役立つかもしれないと思った。しかし、私はそれを使用する方法を理解できませんでした。swift 3でenumerateDateを使用して過去50年間の日曜日をすべて検索するにはどうすればよいですか?

func enumerateDates(startingAfter: Date, matching: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy, direction: Calendar.SearchDirection, using: (Date?, Bool, inout Bool) -> Void) 

答えて

6

次のコードは、最新の日曜日から始まる過去50年間の日曜日を出力します。

let cal = Calendar.current 
// Get the date of 50 years ago today 
let stopDate = cal.date(byAdding: .year, value: -50, to: Date())! 

// We want to find dates that match on Sundays at midnight local time 
var comps = DateComponents() 
comps.weekday = 1 // Sunday 

// Enumerate all of the dates 
cal.enumerateDates(startingAfter: Date(), matching: comps, matchingPolicy: .previousTimePreservingSmallerComponents, repeatedTimePolicy: .first, direction: .backward) { (date, match, stop) in 
    if let date = date { 
     if date < stopDate { 
      stop = true // We've reached the end, exit the loop 
     } else { 
      print("\(date)") // do what you need with the date 
     } 
    } 
} 
+1

あなたは '日付であれば、

+0

@CodeDifferentのおかげを書くことができますので、 'スウィフト3でDate'は同等です。私はそれを忘れてしまった。 – rmaddy

関連する問題