開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.1 Beta
- Swift (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 11(Serious functions: Anonymous Functions, Scope and Closures)、SHARPEN YOUR PENCIL(p.478)をSwiftで考えてみる。
SHARPEN YOUR PENCIL(p.478)
コード(Xcode)
main.swift
// // main.swift // sample478 // // Created by kamimura on 9/19/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation struct Cookies { let instructions:String = "Preheat oven to 350..."; var bake = {(time:UInt32) -> () in println("Baking the cookies.") // time秒 sleep(time) println("Cookies are ready, take them out to cool.") println("Cooling the cookies.") // 5秒 sleep(5) println("Cookies are cool., time to eat!") } } let cookies:Cookies = Cookies() println("Time to bake the sookies.") cookies.bake(10) println() func setTimeout(f:() -> (), time:UInt32) { sleep(time) f() } struct Cookies1 { let instructions:String = "Preheat oven to 350..."; var bake = {(time:UInt32) -> () in println("Baking the cookies.") setTimeout({() -> () in println("Cookies are ready, take them out to cool.") println("Cooling the cookies.") setTimeout({() -> () in println("Cookies are cool, time to eat!") }, 5) }, time) } } let cookies1:Cookies1 = Cookies1() println("Time to bake the sookies.") cookies1.bake(10)
入出力結果(Console Output)
Time to bake the sookies. Baking the cookies. Cookies are ready, take them out to cool. Cooling the cookies. Cookies are cool., time to eat! Time to bake the sookies. Baking the cookies. Cookies are ready, take them out to cool. Cooling the cookies. Cookies are cool, time to eat! Program ended with exit code: 0
0 コメント:
コメントを投稿