Skip to content

Instantly share code, notes, and snippets.

View JohnSundell's full-sized avatar

John Sundell JohnSundell

View GitHub Profile
@JohnSundell
JohnSundell / Namespacing-Swift-code-with-nested-types-1.swift
Created April 1, 2017 21:35
Code sample #2 from my Medium post "Namespacing Swift code with nested types"
struct Post {
class TextFormatter {
enum Option {
case highlightNames
case highlightLinks
}
private let options: Set<Option>
init(options: Set<Option>) {
@JohnSundell
JohnSundell / Namespacing-Swift-code-with-nested-types-1.swift
Created April 1, 2017 21:35
Code sample #2 from my Medium post "Namespacing Swift code with nested types"
struct Post {
class TextFormatter {
enum Option {
case highlightNames
case highlightLinks
}
private let options: Set<Option>
init(options: Set<Option>) {
@JohnSundell
JohnSundell / Namespacing-Swift-code-with-nested-types-0.swift
Created April 1, 2017 21:33
Code sample #1 from my Medium post "Namespacing Swift code with nested types"
struct Post {
let id: Int
let author: User
let title: String
let text: String
}
class PostTextFormatter {
private let options: Set<Option>
@JohnSundell
JohnSundell / ErrorTypeExample.swift
Created March 28, 2017 18:00
Example on how you can name your own types using the same name as a standard libary type
extension Command {
enum Error: Swift.Error {
case missing
case invalid(String)
}
}
func testLoadingData() {
class NetworkEngineMock: NetworkEngine {
typealias Handler = NetworkEngine.Handler
var requestedURL: URL?
func performRequest(for url: URL, completionHandler: @escaping Handler) {
requestedURL = url
let data = “Hello world”.data(using: .utf8)
class DataLoader {
enum Result {
case data(Data)
case error(Error)
}
private let engine: NetworkEngine
init(engine: NetworkEngine = URLSession.shared) {
self.engine = engine
protocol NetworkEngine {
typealias Handler = (Data?, URLResponse?, Error?) -> Void
func performRequest(for url: URL, completionHandler: @escaping Handler)
}
extension URLSession: NetworkEngine {
typealias Handler = NetworkEngine.Handler
func performRequest(for url: URL, completionHandler: @escaping Handler) {
class DataLoader {
enum Result {
case data(Data)
case error(Error)
}
func load(from url: URL, completionHandler: @escaping (Result) -> Void) {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
return completionHandler(.error(error))
class CardGameTests: XCTestCase {
func testDrawingRandomCard() {
var randomizationUpperBound: UInt32?
let deck = Deck(cards: [Card(value: .ace, suite: .spades)])
let game = CardGame(deck: deck, randomizer: { upperBound in
// Capture the upper bound to be able to assert it later
randomizationUpperBound = upperBound
class CardGame {
typealias Randomizer = (UInt32) -> UInt32
private let deck: Deck
private let randomizer: Randomizer
init(deck: Deck, randomizer: @escaping Randomizer = arc4random_uniform) {
self.deck = deck
self.randomizer = randomizer
}