2014年8月11日月曜日

開発環境

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

OBJECT MAGNETS(p.183)

コード(Xcode)

main.swift

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

import Foundation

var dog = ["name":"Fido", "weight":20.2, "age":4, "breed":"mixed", "activity":"fetch balls"]

var bark:String
if dog["weight"].floatValue > 20 {
    bark = "WOOF WOOF"
} else {
    bark = "woof woof"
}

println((dog["name"] as String) + " says " + bark + " when he want to " + (dog["activity"] as String))

class Dog {
    let name:String
    // privateは意味ない?
    private var weight:Float
    var age:Int
    var breed:String
    var activity:String
    
    init(name:String, weight:Float, age:Int, breed:String, activity:String) {
        self.name = name
        self.weight = weight
        self.age = age
        self.breed = breed
        self.activity = activity
    }
    var description:String {
        let bark = weight > 20 ? "WOOF WOOF" : "woof woof"
        return "\(name) says \(bark) when he want to \(activity)"
    }
    func description1() -> String {
        let bark = weight > 20 ? "WOOF WOOF" : "woof woof"
        return "\(name) says \(bark) when he want to \(activity)"
    }
}

var dog1 = Dog(name: "Fido", weight: 20.2, age: 4, breed: "mixed", activity: "fetch balls")
println(dog1.description)
println(dog1.description1())

// private fieldの変数でも値を変更出来るか確認
dog1.weight = 15
println(dog1.description)
println(dog1.description1())

入出力結果(Console Output)

Fido says WOOF WOOF when he want to fetch balls
Fido says WOOF WOOF when he want to fetch balls
Fido says WOOF WOOF when he want to fetch balls
Fido says woof woof when he want to fetch balls
Fido says woof woof when he want to fetch balls
Program ended with exit code: 0

0 コメント:

コメントを投稿