12ヶ月表示をしてみる

投稿者: | 2015年6月15日

さて、3ヶ月表示ができてしまえばあとは簡単。始まり月を1月にして処理を4回繰り返すだけ。

#! /usr/bin/swift
import Foundation
// Date型の引数を受け取り、DateComponents型を返す関数
func getCalComp(date: Date) -> DateComponents {
    let cal: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let components: DateComponents = cal.components([.year, .month, .day, .weekday], from:date)
    return components
}
// 一日始まりのDateComponents型の引数を受け取り、その月の配列を返す関数
func getCalendar(components: DateComponents) -> [String] {
    var cal_seq: [String] = ["日","月","火","水","木","金","土"]
    var endofmonth: [Int] = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (components.year! % 4) == 0 && (components.year! % 100) != 0 || (components.year! % 400) == 0 {
        endofmonth[2]+=1
    }
    for _ in 0..<42 {
        cal_seq.append("  ")
    }
    var datestring: String
    for var i in 1..<endofmonth[components.month!]+1 {
        if i < 10 {
            datestring = " \(i)"
        } else {
            datestring = "\(i)"
        }
        cal_seq[ (6 + i) + (components.weekday! - 1) ] = datestring
    }
    return cal_seq
}
// 実質プログラムの始まり
let je_flag = 1
let now: Date = Date()
var cal_comp: DateComponents = getCalComp(date:now)
cal_comp.month = 1
cal_comp.day = 1
var sequence: [String] = []
var header: String = ""
var header_y: String = ""
var header_m: [String] = ["", "", "", "", "", "", "", "", "", "", "", ""]
for var i in 0..<12 {
    var calen: Date = Calendar.current.date(from:cal_comp)!
    cal_comp = getCalComp(date:calen)
    sequence += getCalendar(components:cal_comp)
    if i == 1 { header_y += "\(cal_comp.year!)" }
    header_m[i] = "\(cal_comp.month!)月"
    cal_comp.month!+=1
}
var length: Int = (65 - header_y.characters.count) / 2
for var i in 0..<length+1 {
    header_y = " " + header_y
}
print("\(header_y)\n")
for var l in 0..<4 {
    for var i in 0..<3 {
        length = (21 - (header_m[i + 3 * l].characters.count + je_flag)) / 2
        for var j in 0..<length {
            header_m[i + 3 * l] = " " + header_m[i + 3 * l]
        }
        length = 22 - (header_m[i + 3 * l].characters.count + je_flag)
        for var j in 0..<length {
            header_m[i + 3 * l] = header_m[i + 3 * l] + " "
        }
        header += header_m[i + 3 * l]
    }
    print(header)
    header = ""
    for var i in 0..<7 {
        for var j in 0..<3 {
            for var k in 0..<7 {
                var address = i * 7 + ((j + 3 * l) * 49 + k)
                print("\(sequence[address]) ", terminator:"")
            }
            print(" ", terminator:"")
        }
        print("")
    }
}

threemonth2.swiftとの違いはわずかです。34行目でcal_comp.monthを強制的に1に書き換え、53行目で3ヶ月表示ブロックを変数lを使って4回まわしています。それからなぜか70行目の計算が複雑ですと怒られたので、一旦配列の外で同じ計算をしてからその結果を使って配列要素を指定するように変更しています。

動作結果はこのとおり。cal -yと同じ結果が得られました。(例によってforループの警告が出ます)

thisyear.swift実行結果

cal -y実行結果