Skip to content

Instantly share code, notes, and snippets.

Ben Cohen airspeedswift

Block or report user

Report or block airspeedswift

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View gist:ec36f164d31d4cf24541
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 Aug 29, 2015
Every combination of every element of two sequences in Swift - ugly brute force version
View combos1.swift
// 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 {
View switching on pairs of optionals
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.
View RemoveDuplicates.swift
// removes all but first occurrence from a sequence, returning an array.
// requires elements to be hashable, not just equatable, but the alternative
// of using contains is very inefficient
// alternatively, could require comparable, sort, and remove adjacent dupes
func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(seq: S) -> [E] {
var seen: [S.Generator.Element:Int] = [:]
return filter(seq) { !seen.updateValue(1, forKey: $0).hasValue }
}
// TODO: a version that takes a custom comparator function, say for lexicographic deduping
View Swift Generic Functions
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
View gist:6c7051b427fa60534c41
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 Aug 29, 2015
Swift for…in generic inference prob
View GenericInfProb.swift
// 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 Aug 29, 2015
Luhn Algorithm for Credit Card Validation using lazy() in Swift
View LuhnAlgorithm.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 Aug 29, 2015
Luhn Algorithm – side by side lazy and eager versions
View LuhnAlgoLazyVsEager.swift
// 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 Aug 29, 2015
Generic ExtensibleCollectionType algorithm plus a default Array version
View ExtensibleCollectionPlusDefault.swift
// 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)
You can’t perform that action at this time.