Skip to content

Instantly share code, notes, and snippets.

View airspeedswift's full-sized avatar

Ben Cohen airspeedswift

View GitHub Profile
func boundsOf<C: Swift.Collection>(c: C) -> Range<C.IndexType> {
return c.startIndex..<c.endIndex
}
/// Return the index of the minimum element in a collection (as defined
/// by a binary predicate) starting from a given point. Empty
/// collections return nil. In case of duplicate minima, returns
/// the index of the first in the collection.
//
@airspeedswift
airspeedswift / combos1.swift
Last active August 29, 2015 14:04
Every combination of every element of two sequences in Swift - ugly brute force version
// after https://twitter.com/cocoaphony/status/490708834415947776
func combinations
<First: SequenceType, Second: CollectionType>
(first: First, second: Second)
-> GeneratorOf<(First.Generator.Element, Second.Generator.Element)> {
var first_gen = first.generate()
var second_gen = second.generate()
var current_first = first_gen.next()
return GeneratorOf {
func optional_pair1<T,U>(t: T?, u: U?)->String {
switch (t,u) {
// every case exhaustively covers the possibilities
case (.None,.None): return "neither"
case let (.Some(t), .Some(u)): return "both"
case let (.Some(t),.None): return "left"
case let (.None,.Some(u)): return "right"
// so no need for a default clause at all
// this way, you are totally explicit about
// which case is being handled how.
func sortedSet<S: RangeReplaceableCollectionType where S.Generator.Element: Comparable>(seq:S, obj:S)-> [S.Generator.Element] {
let s = reduce(seq, obj){
ac, x in contains(ac,x) ? ac : ac + [x]
}
let set = sorted(s){$0<$1}
return set
}
func insert<S:RangeReplaceableCollectionType, I: SignedIntegerType where I == S.Index.Distance, S.Generator.Element: Equatable>(inout seq:S, ins:S, ind:I) {
// use of abs() prevents a negative value causing the insertIndex to be before the startIndex
import KeychainAPI
let keychain: Keychain = Keychain(service: "com.secondgear.myapp", accessibility: Accessibility.WhenUnlocked)
let userAccount = Account(userName: "justinw@me.com", secret: "lovesecretsexgod")
keychain.add(userAccount)
if let fetchedAccount = keychain.accountFor("justinw@me.com")
{
fetchedAccount.secret = "newpassword"
@airspeedswift
airspeedswift / GenericInfProb.swift
Last active August 29, 2015 14:07
Swift for…in generic inference prob
// original version with problem
struct A<T> {
func f<S: SequenceType where S.Generator.Element == T>(s: S) {
// error: cannot convert expression's type S to type S
for v in s {
print(v)
}
}
}
@airspeedswift
airspeedswift / LuhnAlgorithm.swift
Last active August 29, 2015 14:09
Luhn Algorithm for Credit Card Validation using lazy() in Swift
// See @SwiftLDN's tweet for a short description of the Luhn algorithm:
// https://twitter.com/SwiftLDN/status/529412592834338817
// or Wikipedia for a longer one.
// http://en.wikipedia.org/wiki/Luhn_algorithm
//
// Only meant to show extending Swift's lazy() for infotainment purposes,
// not necessarily recommending best or even good practices!
//
// Alternative, saner, solutions here:
@airspeedswift
airspeedswift / LuhnAlgoLazyVsEager.swift
Last active August 29, 2015 14:09
Luhn Algorithm – side by side lazy and eager versions
// Another version of the Luhn algorithm, similar to the one found here:
// https://gist.github.com/airspeedswift/b349c256e90da746b852
//
// This time, trying to keep two versions, one eager one lazy,
// as similar as possible. Only adding "lazy" to the start of
// the expression to switch between the two.
//
// Much of the same code as the previous version at the top,
// Skip down to line 110 for the different part
@airspeedswift
airspeedswift / ExtensibleCollectionPlusDefault.swift
Last active August 29, 2015 14:09
Generic ExtensibleCollectionType algorithm plus a default Array version
// This algorithm returns a generic placeholder
// that can be any kind of extensible collection:
func mapSome
<S: SequenceType, C: ExtensibleCollectionType>
(source: S, transform: (S.Generator.Element)->C.Generator.Element?) -> C {
var result = C()
for x in source {
if let y = transform(x) {
result.append(y)
@airspeedswift
airspeedswift / dropFirst.swift
Last active August 29, 2015 14:10
dropFirst for any SequenceType
func myDropFirst<S: SequenceType>(seq: S) -> SequenceOf<S.Generator.Element> {
return SequenceOf { ()->GeneratorOf<S.Generator.Element> in
var g = seq.generate()
let first = g.next()
// if you prefer your dropFirst to explodinate on empty
// sequences, add an assert(first != nil) here...
return GeneratorOf {
// shouldn't call GeneratorType.next()
// after it's returned nil the first time
first == nil ? nil : g.next()