2014年8月16日土曜日

開発環境

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

EXERCISE(p.207)

コード(Xcode)

main.swift

//
//  main.swift
//  sample207
//
//  Created by kamimura on 8/16/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
    
    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 () {
        self.started = true
    }
    func stop () {
        self.started = false
    }
    func drive () {
        if self.started {
            println("\(self.make) \(self.model) goes zoom zoom!")
        } else {
            println("You need to start the engine first.")
        }
    }
}

let cadi = Car(make: "GM", model: "Cadillac", year: 1955, color: "tan", passengers: 5, convertible: false, mileage: 12892)
let chevy = Car(make: "Chevy", model: "Bel Air", year: 1957, color: "red", passengers: 2, convertible: false, mileage: 1021)
let taxi = Car(make: "Webville Motors", model: "Taxi", year: 1955, color: "yellow", passengers: 4, convertible: false, mileage: 281341)

cadi.start()
cadi.drive()
cadi.stop()
chevy.start()
chevy.drive()
chevy.stop()
taxi.start()
taxi.drive()
taxi.stop()

入出力結果(Console Output)

GM Cadillac goes zoom zoom!
Chevy Bel Air goes zoom zoom!
Webville Motors Taxi goes zoom zoom!
Program ended with exit code: 0

0 コメント:

コメントを投稿