Skip to content

Instantly share code, notes, and snippets.

View BeauNouvelle's full-sized avatar
👨‍💻
Working

Beau Nouvelle BeauNouvelle

👨‍💻
Working
View GitHub Profile
func testRetrieveProductsValidResponse() {
// we have a locally stored product list in JSON format to test against.
let testBundle = Bundle(forClass: type(of: self))
let filepath = testBundle.pathForResource("products", ofType: "txt")
let data = Data(contentsOfFile: filepath!)
let urlResponse = HTTPURLResponse(url: URL(string: "https://anyurl.doesntmatter.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)
// setup our mock response with the above data and fake response.
MockSession.mockResponse = (data, urlResponse: urlResponse, error: nil)
let requestsClass = RequestManager()
// All our network calls are in here.
@BeauNouvelle
BeauNouvelle / UIBarButtonItem Closure 1.swift
Last active April 11, 2019 02:46
UIBarButtonItem Closure
extension UIBarButtonItem {
/// Typealias for UIBarButtonItem closure.
private typealias UIBarButtonItemTargetClosure = (UIBarButtonItem) -> ()
private class UIBarButtonItemClosureWrapper: NSObject {
let closure: UIBarButtonItemTargetClosure
init(_ closure: @escaping UIBarButtonItemTargetClosure) {
self.closure = closure
}
convenience init(title: String?, style: UIBarButtonItem.Style, closure: @escaping UIBarButtonItemTargetClosure) {
self.init(title: title, style: style, target: nil, action: nil)
targetClosure = closure
action = #selector(UIBarButtonItem.closureAction)
}
@objc func closureAction() {
guard let targetClosure = targetClosure else { return }
targetClosure(self)
}
// Old way of doing things.
let actionButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(someMethod()))
// New way of doing things.
let button = UIBarButtonItem(title: "Done", style: .done) { _ in
// Do stuff here.
}
// Add to UIButton extension.
public func touchUpInside(closure: @escaping UIButtonTargetClosure) {
targetClosure = closure
addTarget(self, action: #selector(UIButton.closureAction), for: .touchUpInside)
}
// Useage
let button = UIButton()
button.touchUpInside { _ in
// Do stuff.
public enum State {
case alive
case dead
}
public struct Cell {
public let x: Int
public let y: Int
public var state: State
}
public init(x: Int, y: Int, state: State) {
self.x = x
self.y = y
self.state = state
}
public func isNeighbor(to cell: Cell) -> Bool {
let xDelta = abs(self.x - cell.x)
let yDelta = abs(self.y - cell.y)
switch (xDelta, yDelta) {
case (1, 1), (0, 1), (1, 0):
return true
default:
return false
let firstCell = Cell(x: 10, y: 10, state: .dead)
let secondCell = Cell(x: 11, y: 11, state: .dead)
print(firstCell.isNeighbor(to: secondCell))
// true - Adjacent row, adjacent column.