「リファクタリング 第2版」Swiftでコーディング その2

リファクタリング 第2版

7頁 第1章 amountFor関数、8頁 第1章 statement関数

Swift版 main.swift

データ生成、結果表示付き。

import Foundation

makeData()

func statement(invoice:Invoice, plays:Dictionary<String, Play>) -> String {
    var volumeCredits = 0
    var totalAmount = 0
    var result = "Statement for \(invoice.customer)\n"
    let format = NumberFormatter()
    format.numberStyle = .currency
    format.locale = Locale(identifier: "en_US")

    for perf in invoice.performances {
        let play = plays[perf.playID]!
        let thisAcmount = amountFor(perf: perf, play: play)

        volumeCredits += max(perf.audience - 30, 0)
        if "comedy" == play.type {
            volumeCredits += Int(perf.audience / 5)
        }
        result += "  \(play.name): " + format.string(from: NSNumber(value: thisAcmount / 100))! + " (\(perf.audience) seats)\n"
        totalAmount += thisAcmount
    }
    result += "Amount owed is " + format.string(from: NSNumber(value: totalAmount / 100))! + "\n"
    result += "You earned \(volumeCredits) credits\n"
    return result
}

func amountFor(perf:Performance, play:Play) -> Int {
    var thisAcmount = 0

    switch play.type {
    case "tragedy":
        thisAcmount = 40000
        if perf.audience > 30 {
            thisAcmount += 1000 * (perf.audience - 30)
        }
    case "comedy":
        thisAcmount = 30000
        if perf.audience > 20 {
            thisAcmount += 10000 + 500 * (perf.audience - 20)
        }
        thisAcmount += 300 * perf.audience
    default:
        print("error")
    }
    return thisAcmount
}

let result = statement(invoice: invoices[0], plays: plays)
print(result)

Swift

Posted by shi-n