Last active
January 26, 2016 17:22
-
-
Save citizen428/b396df1abb1a252881f4 to your computer and use it in GitHub Desktop.
Turning Swift into Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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