2014年8月1日金曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 3(Introducing Functions: Getting functional)、SHARPEN YOUR PENCIL(p.86)、CODE MAGNETS(p.87)をSwiftで考えてみる。

SHARPEN YOUR PENCIL(p.86)、CODE MAGNETS(p.87)

コード(Xcode)

main.swift

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

import Foundation

func input(msg:String = "") -> String {
    print(msg)
    var in_fh = NSFileHandle.fileHandleWithStandardInput()
    var data = in_fh.availableData
    var s = NSString(data: data, encoding: NSUTF8StringEncoding)
    s = s.substringToIndex(s.length - 1)
    return s;
}

func bark(name:String, weight:Int) {
    if weight > 20 {
        println("\(name) says WOOF WOOF")
    } else {
        println("\(name) says woof woof");
    }
}

func whatShallIWear(temp:Float) {
    switch temp {
    case let x where x < 10:
        println("Wear a jacket")
    case let x where x < 20:
        println("Wear a sweater")
    default:
        println("Wear t-shirt")
    }
}

var dogs = Dictionary<String, Int>()
dogs = ["juno":20, "scottie":-1, "dino":0, "fido":10, "lady":10, "bruno":21]
for (name, weight) in dogs {
    bark(name, weight)
}

whatShallIWear(5)
whatShallIWear(25)
whatShallIWear(15)

while true {
    let temperature = input(msg: "気温: ")
    if temperature == "" {
        break
    }
    whatShallIWear(Float(temperature.toInt()!))
}

入出力結果(Console Output)

scottie says woof woof
juno says woof woof
fido says woof woof
lady says woof woof
bruno says WOOF WOOF
dino says woof woof
Wear a jacket
Wear t-shirt
Wear a sweater
気温: 9
Wear a jacket
気温: 10
Wear a sweater
気温: 19
Wear a sweater
気温: 20
Wear t-shirt
気温: 
Program ended with exit code: 0

0 コメント:

コメントを投稿