「リファクタリング 第2版」Swiftでコーディング その12
リファクタリング 第2版
17頁 第1章 format変数の削除
Swift版 main.swift
データ生成、結果表示付き。
import Foundation makeData() func playFor(aPerformance:Performance) -> Play { return plays[aPerformance.playID]! } func volumeCreditsFor(aPerformance:Performance) -> Int { var result = 0 result += max(aPerformance.audience - 30, 0) if "comedy" == playFor(aPerformance: aPerformance).type { result += Int(aPerformance.audience / 5) } return result } func format(aNumber:Int) -> String { let format = NumberFormatter() format.numberStyle = .currency format.locale = Locale(identifier: "en_US") return format.string(from: NSNumber(value: aNumber))! } func statement(invoice:Invoice, plays:Dictionary<String, Play>) -> String { var volumeCredits = 0 var totalAmount = 0 var result = "Statement for \(invoice.customer)\n" for perf in invoice.performances { volumeCredits += volumeCreditsFor(aPerformance: perf) result += " \(playFor(aPerformance: perf).name): " + format(aNumber: amountFor(aPerformance: perf) / 100) + " (\(perf.audience) seats)\n" totalAmount += amountFor(aPerformance: perf) } result += "Amount owed is " + format(aNumber: totalAmount / 100) + "\n" result += "You earned \(volumeCredits) credits\n" return result } func amountFor(aPerformance:Performance) -> Int { var result = 0 switch playFor(aPerformance: aPerformance).type { case "tragedy": result = 40000 if aPerformance.audience > 30 { result += 1000 * (aPerformance.audience - 30) } case "comedy": result = 30000 if aPerformance.audience > 20 { result += 10000 + 500 * (aPerformance.audience - 20) } result += 300 * aPerformance.audience default: print("error") } return result } let result = statement(invoice: invoices[0], plays: plays) print(result)