開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 10(Liberated functions: First Class Functions)、EXERCISE(p.456)をSwiftで考えてみる。
EXERCISE(p.456)
コード(Xcode)
main.swift
// // main.swift // sample456 // // Created by kamimura on 9/12/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation struct Passenger { let name:String let paid:Bool let ticket:String } let passengers:[Passenger] = [ Passenger(name: "Jane Doloop", paid: true, ticket: "firstclass"), Passenger(name: "Dr. Evel", paid: true, ticket: "coach"), Passenger(name: "Sue Property", paid: false, ticket:"premium"), Passenger(name: "John Funcall", paid: true, ticket:"coach") ] func createDrinkOrder(passenger:Passenger) -> () -> () { var orderFunc:() -> () if passenger.ticket == "firstclass" { orderFunc = {() in println("Would you like a cocktail or wine?")} } else if passenger.ticket == "premium" { orderFunc = {() in println("Would you like wine, cola or water?")} } else { orderFunc = {() in println("Would you like cola or water?")} } return orderFunc } func createDinnerFunc(passenger:Passenger) -> () -> () { var orderFunc:() -> () if passenger.ticket == "firstclass" { orderFunc = {() in println("Would you like chicken or pasta?")} } else if passenger.ticket == "premium" { orderFunc = {() in println("Would you like a snack box or cheese plate?")} } else { orderFunc = {() in println("Would you like peanuts or pretzels?")} } return orderFunc } func serveCustomer(passenger:Passenger) { let getDrinkOrderFunc:() -> () = createDrinkOrder(passenger) let getDinnerOrderFunc:() -> () = createDinnerFunc(passenger) getDrinkOrderFunc() getDrinkOrderFunc() getDinnerOrderFunc() getDrinkOrderFunc() getDrinkOrderFunc() } func servePassengers(passengers:[Passenger]) { for passenger in passengers { println("\(passenger.name), \(passenger.ticket)") serveCustomer(passenger) } } servePassengers(passengers)
入出力結果(Console Output)
Jane Doloop, firstclass Would you like a cocktail or wine? Would you like a cocktail or wine? Would you like chicken or pasta? Would you like a cocktail or wine? Would you like a cocktail or wine? Dr. Evel, coach Would you like cola or water? Would you like cola or water? Would you like peanuts or pretzels? Would you like cola or water? Would you like cola or water? Sue Property, premium Would you like wine, cola or water? Would you like wine, cola or water? Would you like a snack box or cheese plate? Would you like wine, cola or water? Would you like wine, cola or water? John Funcall, coach Would you like cola or water? Would you like cola or water? Would you like peanuts or pretzels? Would you like cola or water? Would you like cola or water? Program ended with exit code: 0
0 コメント:
コメントを投稿