開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta 6
- Swift (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 9(Repeating Code Using Loops)、9.10(Exercises) 6.をSwiftで考えてみる。
9.10(Exercises) 6.
コード(Xcode)
main.swift
// // main.swift // sample6 // // Created by kamimura on 9/7/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation var text:String = "" while text.lowercaseString != "quit" { text = input() switch text { case let s where s.lowercaseString == "quit": println("…exiting program") case "H2O": println("Water") case "NH3": println("Ammonia") case "CH4": println("Methane") default: println("Unknown compound") } }
stdio.swift
// // stdio.swift // stdio // // Created by kamimura on 8/21/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation // 標準入力(STDIN)から読み込む 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 read(path:String) -> String? { return String.stringWithContentsOfFile(path) } func print(s:String, path:String, end:String = "\n") { (s + end).writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil) } func error(msg:String) { let stderr = NSFileHandle.fileHandleWithStandardError() stderr.writeData((msg + "\n").dataUsingEncoding(NSUTF8StringEncoding)!) exit(1) } // コマンドライン引数 let argv:[String] = NSProcessInfo.processInfo().arguments.map({(x:AnyObject) -> String in x as String})
入出力結果(Console Output)
$ ./sample6 quit …exiting program $ ./sample6 Quit …exiting program $ ./sample6 QUIT …exiting program $
0 コメント:
コメントを投稿