2014年9月8日月曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数: 関数を最大限に活用する)、長いエクササイズ(p.328)をSwiftで考えてみる。

長いエクササイズ(p.328)

コード(Xcode)

main.swift

//
//  main.swift
//  sample328
//
//  Created by kamimura on 9/8/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

struct Rectangle : Printable {
    let width:Int
    let height:Int
    var area:Int { return width * height }
    var description: String { return "\(width)x\(height)" }
}

func compareScores(a:Int, b:Int) -> Bool {
    return a < b;
}

func compareAreas(a:Rectangle, b:Rectangle) -> Bool {
    return a.area < b.area
}

func compareNames(a:String, b:String) -> Bool {
    return a < b
}

func compareAreasDesc(a:Rectangle, b:Rectangle) -> Bool {
    return compareAreas(b, a)
}

func compareNamesDesc(a:String, b:String) -> Bool {
    return compareNames(b, a)
}

var nums:[Int] = [5, 1, 4, 2, 3]
var rs:[Rectangle] = [Rectangle(width: 1, height: 5), Rectangle(width: 1, height: 1), Rectangle(width: 1, height: 4),
    Rectangle(width: 1, height: 2), Rectangle(width: 1, height: 3)]
var strs:[String] = ["Abc", "Def"]

println("sorted")
println(nums.sorted({(a:Int, b:Int) in a < b}))
println(nums)
println(nums.sorted({(a:Int, b:Int) in a > b}))
println(nums)

println(rs.sorted(compareAreas))
println(rs)
println(rs.sorted(compareAreasDesc))
println(rs)

println(strs.sorted(compareNames))
println(strs)
println(strs.sorted(compareNamesDesc))
println(strs)

println("sort")
nums.sort({(a:Int, b:Int) in a < b})
println(nums)
nums.sort({(a:Int, b:Int) in a > b})
println(nums)

rs.sort(compareAreas)
println(rs)
rs.sort(compareAreasDesc)
println(rs)

strs.sort(compareNames)
println(strs)
strs.sort(compareNamesDesc)
println(strs)

入出力結果(Console Output, Terminal)

sorted
[1, 2, 3, 4, 5]
[5, 1, 4, 2, 3]
[5, 4, 3, 2, 1]
[5, 1, 4, 2, 3]
[1x1, 1x2, 1x3, 1x4, 1x5]
[1x5, 1x1, 1x4, 1x2, 1x3]
[1x5, 1x4, 1x3, 1x2, 1x1]
[1x5, 1x1, 1x4, 1x2, 1x3]
[Abc, Def]
[Abc, Def]
[Def, Abc]
[Abc, Def]
sort
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1x1, 1x2, 1x3, 1x4, 1x5]
[1x5, 1x4, 1x3, 1x2, 1x1]
[Abc, Def]
[Def, Abc]
Program ended with exit code: 0

0 コメント:

コメントを投稿