開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 8(Storing Collections of Data Using Array)、8.9(Exercises) 6-a, b, c, d.をSwiftで考えてみる。
8.9(Exercises) 6-a, b, c, d.
コード(Xcode)
main.swift
// // main.swift // sample6 // // Created by kamimura on 8/25/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation println("a.") var temps:[Double] = [25.2, 16.8, 31.4, 23.9, 28, 22.5, 19.6] println(temps) println("b.") temps.sort({(a:Double, b:Double) in a < b}) println(temps) println("c.") let cool_temps = temps.slice(end: 2) let warm_temps = temps.slice(start: 2) println(cool_temps) println(warm_temps) println("d.") let temps_in_celsius = cool_temps + warm_temps println(temps_in_celsius)
array.swift
// // array.swift // array // // Created by kamimura on 8/21/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation extension Array { func indexAt(i:Int) -> T { if i >= 0 { return self[i] } let new_index:Int = self.count + i return self[new_index] } func slice(start:Int = 0, end:Int? = nil) -> Array { var new_start = start >= 0 ? start : self.count + start var new_end:Int if end == nil { new_end = self.count } else if end! >= 0 { new_end = end! } else { new_end = self.count + end! } var result:Array = [] if new_start >= new_end { return [] } for i in new_start..<new_end { result.append(self[i]) } return result } }
入出力結果(Console Output)
a. [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6] b. [16.8, 19.6, 22.5, 23.9, 25.2, 28.0, 31.4] c. [16.8, 19.6] [22.5, 23.9, 25.2, 28.0, 31.4] d. [16.8, 19.6, 22.5, 23.9, 25.2, 28.0, 31.4] Program ended with exit code: 0
0 コメント:
コメントを投稿