2014年8月24日日曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 7(Types, Equality, Conversion and All That Jazz: Serious types))、SHARPEN YOUR PENCIL(p.290)をSwiftで考えてみる。

SHARPEN YOUR PENCIL(p.290)

コード(Xcode)

main.swift

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

import Foundation

println("class(===)")
class Car {
    var make:String
    var model:String
    init(make:String, model:String) {
        self.make = make
        self.model = model
    }
}

var chevy:Car = Car(make: "Chevy", model: "Bel Air")
var taxi:Car = Car(make: "Webville Motors", model: "Taxi")
var fiat1:Car = Car(make: "Fiat", model: "500")
var fiat2:Car = Car(make: "Fiat", model: "500")
var lot:[Car] = [chevy, taxi, fiat1, fiat2]

func findCarInLot(car:Car) -> Int? {
    for i in 0..<lot.count {
        if car === lot[i] {
            return i
        }
    }
    return  nil
}

println(findCarInLot(fiat2)!) // 3 (fiat1 == fiat2 is false)
println(findCarInLot(taxi)!)  // 1
println(findCarInLot(chevy)!) // 0
println(findCarInLot(fiat1)!) // 2

println("Dictionary(==)")
let chevy1 = ["make":"Chevy", "model":"Bel Air"]
let taxi1 = ["make":"Webville Motors", "model":"Taxi"]
let fiat3 = ["make":"Fiat", "model":"500"]
let fiat4 = ["make":"Fiat", "model":"500"]
let lot1 = [chevy1, taxi1, fiat3, fiat4]

func findCarInLot1(car:Dictionary<String, String>) -> Int? {
    for i in 0..<lot1.count {
        if car == lot1[i] {
            return i
        }
    }
    return nil
}

println(findCarInLot1(fiat4)!)  // 2 (fiat3 == fiat 4 is true)
println(findCarInLot1(taxi1)!)  // 1
println(findCarInLot1(chevy1)!) // 0
println(findCarInLot1(fiat3)!)  // 2

入出力結果(Console Output)

class(===)
3
1
0
2
Dictionary(==)
2
1
0
2
Program ended with exit code: 0

0 コメント:

コメントを投稿