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

リファクタリング 第2版

2頁 第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]!
        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")
        }

        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
}

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

データ生成 data.swift

import Foundation

let json_plays = """
{
"hamlet": {"name": "Hamlet", "type": "tragedy"},
"aslike": {"name": "As You Like It", "type": "comedy"},
"othello": {"name": "Othello", "type": "tragedy"}
}
"""

let json_invoices = """
[
{
"customer": "BigCo",
"performances": [
{
"playID": "hamlet",
"audience": 55
},
{
"playID": "aslike",
"audience": 35
},
{
"playID": "othello",
"audience": 40
}
]
}
]
"""

struct Play: Codable {
    let name: String
    let type: String
}

struct Plays: Codable {
    let hamlet: Play
    let aslike: Play
    let othello: Play
}

struct Performance: Codable {
    let playID: String
    let audience: Int
}

struct Invoice: Codable {
    let customer: String
    let performances:[Performance]
}

let json_plays_data: Data =  json_plays.data(using: String.Encoding.utf8)!
let json_invoices_data:Data = json_invoices.data(using: String.Encoding.utf8)!

var plays:Dictionary<String, Play> = [:]
var invoices:[Invoice] = []

func makeData() {
    let decoder: JSONDecoder = JSONDecoder()

    do {
        let json: Plays = try decoder.decode(Plays.self, from: json_plays_data)
        plays["hamlet"] = json.hamlet
        plays["aslike"] = json.aslike
        plays["othello"] = json.othello
        
    } catch {
        print("error:", error.localizedDescription)
    }

    do {
        let json = try decoder.decode([Invoice].self, from: json_invoices_data)
        invoices = json
    } catch {
        print("error:", error.localizedDescription)
    }

//    print(plays)
//    print(invoices)
}

Swift

Posted by shi-n