開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 6(A Modular Approach to Program)、6.6(Exercises) 2-a, b, c, d, e, f, g.をSwiftで考えてみる。
6.6(Exercises) 2-a, b, c, d, e, f, g.
コード(Xcode)
calendar.swift
//
//  calendar.swift
//  sample2
//
//  Created by kamimura on 8/8/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//
import Foundation
func isLeap(year:Int) -> Bool {
    if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
        return true
    }
    return false
}
func leapdays(y1:Int, y2:Int) -> Int {
    var days = 0
    for year:Int in y1..<y2 {
        if isLeap(year) {
            days += 1
        }
    }
    return days
}
func getWeekday(year:Int, month:Int, day:Int) -> String {
    var date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    var comps = calendar.components(NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit, fromDate: date)
    comps.year = year
    comps.month = month
    comps.day = day
    date = calendar.dateFromComponents(comps)
    let weekday = calendar.components(NSCalendarUnit.WeekdayCalendarUnit, fromDate: date)
    let date_formatter = NSDateFormatter()
    date_formatter.dateFormat = "E"
    return date_formatter.stringFromDate(date)
}
main.swift
// // main.swift // sample2 // // Created by kamimura on 8/8/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation println(isLeap(2014)) println(leapdays(2000, 2051)) println(getWeekday(2016, 7, 29))
入出力結果(Console Output)
false 13 Fri Program ended with exit code: 0
 
0 コメント:
コメントを投稿