2014年8月14日木曜日

開発環境

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

BE THE BROWSER(p.203)

コード(Xcode)

main.swift

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

import Foundation

// Dictionaryと無名関数を使って、JavaScript時と似たように定義してみたけど、build suceededとならなかった。selfはclassに使えても、Dictionary自身を指すようには使えないのかなぁ。
//var song = [
//    "name":"Walk This Way",
//    "artist": "Run-D.M.C",
//    "minutes":4,
//    "seconds":3,
//    "genre": "80s",
//    "playing": false,
//    "play": {() in
//        if !self["playing"] {
//            self["playing"] = true
//            println("Playing " + self["name"] + " by " + self["artist"])
//        }
//    },
//    "pause": {() in
//        if self["playing"] {
//            self["playing"] = false
//        }
//    }
//]

class Song {
    var name:String
    var artist:String
    var minutes:Int
    var seconds:Int
    var genre:String
    var playing:Bool = false
    init(name:String, artist:String, minutes:Int, seconds:Int, genre:String) {
        self.name = name
        self.artist = artist
        self.minutes = minutes
        self.seconds = seconds
        self.genre = genre
    }
    func play() {
        if !playing {
            playing = true
            println("Playing \(name) by \(artist)")
        }
    }
    func pause() {
        if playing {
            playing = false
        }
    }
}

var song:Song = Song(name: "Walk This Way", artist: "Run-D.M.C", minutes: 4, seconds: 3, genre: "80s")

song.play()
song.pause()

入出力結果(Console Output)

Playing Walk This Way by Run-D.M.C
Program ended with exit code: 0

0 コメント:

コメントを投稿