2014年8月17日日曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 5(Understanding Objects: A trip to Objectville)、EXERCISE(p.212)をSwiftで考えてみる。

EXERCISE(p.212)

コード(Xcode)

main.swift

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

import Foundation

class Car {
    let make:String
    let model:String
    let year:Int
    let color:String
    let passengers:Int
    var convertible:Bool
    var mileage:Int
    var started:Bool = false
    var fuel:Int = 0
    
    init(make:String, model:String, year:Int, color:String, passengers:Int, convertible:Bool, mileage:Int) {
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        self.passengers = passengers
        self.convertible = convertible
        self.mileage = mileage
    }
    
    func start () {
        if self.fuel > 0 {
            self.started = true
        } else {
            println("The car is on empty, fill up before starting!")
        }
    }
    func stop () {
        self.started = false
    }
    func drive () {
        if self.started {
            if self.fuel > 0 {
                println("\(self.make) \(self.model) goes zoom zoom!")
                self.fuel -= 1
            } else {
                println("Uh oh, out of fuel.")
                self.stop()
            }
        } else {
            println("You need to start the engine first.")
        }
    }
    func addFuel (amount:Int) {
        self.fuel += amount
    }
}

let fiat = Car(make: "GM", model: "Cadillac", year: 1955, color: "tan", passengers: 5, convertible: false, mileage: 12892)

fiat.start()
fiat.drive()
fiat.addFuel(2)
fiat.start()
fiat.drive()
fiat.drive()
fiat.drive()
fiat.stop()

入出力結果(Console Output)

The car is on empty, fill up before starting!
You need to start the engine first.
GM Cadillac goes zoom zoom!
GM Cadillac goes zoom zoom!
Uh oh, out of fuel.
Program ended with exit code: 0

0 コメント:

コメントを投稿