開発環境
- 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)、EXERCISE(p.500)をSwiftで考えてみる。
EXERCISE(p.500)
コード(Xcode)
main.swift
//
// main.swift
// sample500
//
// Created by kamimura on 9/21/14.
// Copyright (c) 2014 kamimura. All rights reserved.
//
import Foundation
func makePassword(password:String) -> String -> Bool {
return {(password_guess:String) in password_guess == password}
}
func mult(n:Int) -> Int -> Int {
return {(result:Int) in result * n}
}
struct S {
let increment:() -> Int
}
func makeCounter() -> S {
var count:Int = 0
return S(increment: {() in
count += 1
return count
})
}
let p1 = makePassword("pass1")
let p2 = makePassword("pass2")
let mult5 = mult(5)
let mult10 = mult(10)
let c1 = makeCounter()
let c2 = makeCounter()
println(p1("pass1"))
println(p1("pass2"))
println(p2("pass1"))
println(p2("pass2"))
println(mult5(15))
println(mult5(20))
println(mult10(15))
println(mult10(20))
println(c1.increment())
println(c1.increment())
println(c2.increment())
println(c2.increment())
入出力結果(Console Output)
true false false true 75 100 150 200 1 2 1 2 Program ended with exit code: 0
0 コメント:
コメントを投稿