Skip to content

Instantly share code, notes, and snippets.

@citizen428
Last active January 26, 2016 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citizen428/b396df1abb1a252881f4 to your computer and use it in GitHub Desktop.
Save citizen428/b396df1abb1a252881f4 to your computer and use it in GitHub Desktop.
Turning Swift into Ruby
import Foundation
extension Array {
func each(task: (Element) -> ()) {
for element in self {
task(element)
}
}
func eachWithIndex(start: Int? = nil, task: (Int, Element) -> ()) {
let add = start ?? 0
for (index, element) in enumerate() {
task(index + add, element)
}
}
func zip<U>(other: [U]) -> [(Element, U)] {
var result: [(Element, U)] = []
for (index, element) in enumerate() {
if index >= other.count {
break
}
result.append((element, other[index]))
}
return result
}
}
let test = ["a", "b", "c"]
test.eachWithIndex(1) { print("\($0): \($1)") }
// 1: a
// 2: b
// 3: c
test.zip([1, 2]).each { print($0) }
// ("a", 1)
// ("b", 2)
import Foundation
enum Compare: Int {
case Right = -1, Equal, Left
}
infix operator <=> {}
func <=> <T: Comparable>(left: T, right: T) -> Compare {
if left == right {
return .Equal
} else if left > right {
return .Left
} else {
return .Right
}
}
1 <=> 1 // .Equal
2.4 <=> 2.9 // .Right
"b" <=> "a" // .Left
(0 <=> 1).rawValue // -1
switch 0 <=> 1 {
case .Equal, .Left: print("That's odd")
default: print("All good")
}
// prints "All good"
import Foundation
extension Int {
var hours: Int {
return self * 3600
}
var ago: NSDate {
return NSDate().dateByAddingTimeInterval(-NSTimeInterval(self))
}
var fromNow: NSDate {
return NSDate().dateByAddingTimeInterval(NSTimeInterval(self))
}
func times(task: (Int) -> ()) {
for i in 0..<self { task(i) }
}
}
print(NSDate()) // 2016-01-08 09:19:20 +0000
print(3.hours.ago) // 2016-01-08 06:19:20 +0000
print(2.hours.fromNow) // 2016-01-08 11:19:55 +0000
2.times { print($0) } // prints 0 and 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment