Skip to content

Instantly share code, notes, and snippets.

@cjnevin
cjnevin / UIColor+Hex.swift
Last active November 29, 2017 01:07
Convert RGB(A) hex string to UIColor
import UIKit
fileprivate extension Int {
var rgbaPercentage: CGFloat {
return CGFloat(self) / 255.0
}
}
enum UIColorInputError: Error {
case invalidInputColor
//
// LoopingIterator.swift
//
// Created by Chris Nevin on 01/11/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import Foundation
public struct LoopingIterator<Base: Collection> : IteratorProtocol {
@cjnevin
cjnevin / FoldArray.swift
Last active November 29, 2017 01:08
FoldArray
func fold(_ array: [Int], times: Int) -> [Int] {
let m = array.count / 2
let middle = (array.count & 1 == 1 ? [array[m]] : [])
return times > 0 ? fold(zip(array.prefix(m), array.suffix(m).reversed()).map({ $0 + $1 }) + middle, times: times - 1) : array
}
fold([1,2,3,4,5], times: 2)
@cjnevin
cjnevin / LoginUseCase.swift
Last active November 29, 2017 01:08
Login UseCase/Repository/Service setup
//: Domain
struct User {
let firstName: String
let lastName: String
}
struct LoginUseCase {
enum Error: Swift.Error {
case invalidCredentials
let replacements = [("3", "*"), ("7", "3"), ("*", "7")]
func twisted37(_ val: Int) -> Int {
return Int(replacements.reduce(String(val), { $0.replacingOccurrences(of: $1.0, with: $1.1) })) ?? 0
}
func sortTwisted37(_ arr: [Int]) -> [Int] {
return arr.sorted(by: { twisted37($0) < twisted37($1) })
}
assert(sortTwisted37([1,2,3,4,5,6,7,8,9]) == [1, 2, 7, 4, 5, 6, 3, 8, 9])
import Foundation
import RxSwift
import Nimble
class Mock<T> {
private var object: T
private var count: Int = 0
init(object: T) {
self.object = object
@cjnevin
cjnevin / JsonParser.swift
Last active November 29, 2017 01:05
JsonParser
import Foundation
protocol JsonDeserializable {
init(json: Any) throws
}
struct JsonParser {
enum Error: Swift.Error {
case invalidKey(String)
case invalidJson
@cjnevin
cjnevin / GetListUseCase.swift
Last active November 29, 2017 01:06
Return a paged list of results from a repository
import RxSwift
struct List {
struct Item {
let name: String
}
let items: [Item]
}
protocol GetListRepository {
@cjnevin
cjnevin / GetListUseCase-Variable Page Size.swift
Last active February 3, 2018 14:21
Revised for updating count based on response
protocol GetListRepository {
func get(uniqueId: String, startingAt offset: Int, limit: Int) -> Single<List>
}
struct GetListUseCase {
enum Result {
case success(List)
case failure(Error, Int)
}
@cjnevin
cjnevin / VIPERConcept.swift
Last active November 23, 2021 19:53
Concept
class Presenter<T> {
private var view: T?
func attachView(_ view: T) {
self.view = view
}
func detachView() {
self.view = nil
}