2014年8月23日土曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の4章(複数のソースファイルの使用: 分割して構築する)、エクササイズ(p.165)をSwiftで考えてみる。

エクササイズ(p.165)

コード(Xcode)

main.swift

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

import Foundation

var total:Double = 0
var count:Int = 0
let tax_percent:Double = 6

func addWithTax(f:Double) -> Double {
    let tax_rate:Double = 1 + Double(tax_percent) / 100
    total += f * tax_rate
    count += 1
    return total
}

var s:String = input(msg: "品目の値段:")

while s != "" {
    let val:Double = s.doubleValue
    println("ここまでの合計:\(round(addWithTax(val) * 100) / 100)")
    s = input(msg: "品目の値段:")
}
println("最終合計:\(round(total * 100) / 100)")
println("品目数:\(count)")

string.swift

//
//  string.swift
//  string
//
//  Created by kamimura on 8/10/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

extension String {
    var swapcaseString:String {
    var result: String = ""
        for ch in self {
            let s = String(ch)
            result += s.uppercaseString == s ? s.lowercaseString : s.uppercaseString
        }
        return result
    }
    var isUpper:Bool { return self.uppercaseString == self }
    var isLower:Bool { return self.lowercaseString == self }
    var length:Int { return (self as NSString).length }
    var strip:String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())}
    var floatValue:Float { return (self as NSString).floatValue }
    var doubleValue:Double { return (self as NSString).doubleValue }
    func count(sub:String) -> Int {
        var result:Int = 0
        var s = self
        let index:String.Index = "a".endIndex
        while s != "" {
            if s.hasPrefix(sub) {
                result += 1
                s = s.substringFromIndex(sub.endIndex)
            } else {
                s = s.substringFromIndex(index)
            }
            
        }
        return result
    }
    func find(sub:String, start:Int = 0, end:Int? = nil) -> Int {
        var s = self as NSString
        var s_temp = s.substringFromIndex(start)
        let end_temp:Int = end ? end! : s.length
        for i in start..<end_temp {
            if (s_temp.hasPrefix(sub)) {
                return i
            }
            s_temp = s.substringFromIndex(i + 1) as NSString
        }
        return -1
    }
    func replace(old_str:String, new_str:String) -> String {
        return self.stringByReplacingOccurrencesOfString(old_str, withString: new_str)
    }
    func slice(start:Int=0, end:Int?=nil) -> String {
        let s = self as NSString
        var new_end:Int
        if (end) {
            new_end = end!
        } else {
            new_end = s.length
        }
        return  s.substringWithRange(NSRange(location: start, length:new_end - start))
    }
    func split(sep:String = "") -> [String] {
        var result:[String] = []
        if (sep == "") {
            for ch in self {
                result.append(String(ch))
            }
            return result
        }
        var s:String = self
        var len = sep.length
        var temp:String = ""
        while s != "" {
            if s.hasPrefix(sep) {
                if temp != "" {
                    result.append(temp)
                    temp = ""
                }
                s = s.slice(start: len)
            } else {
                temp += s.slice(start: 0, end: 1)
                s = s.slice(start: 1)
            }
        }
        if temp != "" {
            result.append(temp)
        }
        return result
    }
    var reversed:String { return "".join(self.split().reverse()) }
}

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, Terminal)

品目の値段:12.34
ここまでの合計:13.08
品目の値段:56.78
ここまでの合計:73.27
品目の値段:90.12
ここまでの合計:168.79
品目の値段:12345.67
ここまでの合計:13255.2
品目の値段:1.2
ここまでの合計:13256.48
品目の値段:
最終合計:13256.48
品目数:5
Program ended with exit code: 0

0 コメント:

コメントを投稿