開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 3(Introducing Functions: Getting functional)、EXERCISE(p.110)をSwiftで考えてみる。
EXERCISE(p.110)
コード(Xcode)
main.swift
// // main.swift // sample110 // // Created by kamimura on 8/2/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation var clunkCounter:Int = 0 func input(msg:String = "") -> String { print(msg) var in_fh = NSFileHandle.fileHandleWithStandardInput() var data = in_fh.availableData var s = NSString(data: data, encoding: NSUTF8StringEncoding) s = s.substringToIndex(s.length - 1) return s; } func clunk (times:Int) { var num = times while num > 0 { display("clunk"); num -= 1 } } func thingamajig (size: Int) { var facky = 1 clunkCounter = 0 switch size { case 0: display("clank") case 1: display("thunk") default: var t = size while t > 1 { facky *= t t -= 1 } clunk(facky) } println(clunkCounter) } func display (output:String) { println(output) clunkCounter += 1 } thingamajig(5) println(clunkCounter) while true { let s = input(msg: "整数を入力: ") if s == "" { break } thingamajig(s.toInt()!) }
入出力結果(Console Output)
clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk 120 120 整数を入力: 0 clank 1 整数を入力: 1 thunk 1 整数を入力: 2 clunk clunk 2 整数を入力: 3 clunk clunk clunk clunk clunk clunk 6 整数を入力: 4 clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk clunk 24 整数を入力: Program ended with exit code: 0
0 コメント:
コメントを投稿