Skip to content

Instantly share code, notes, and snippets.

View SynchroneHTTPRequest.swift
// A simple network stack I use for my command line tools written in Swift.
// The dataTask here work only for GET operations.
protocol Operation {
associatedtype T: Codable
enum HTTPMethod {
case GET
case POST
case PUT
View ReadStandardInput.swift
func input(_ block: (UInt8) -> (Bool)) {
func initStruct<S>() -> S {
let struct_pointer = UnsafeMutablePointer<S>.allocate(capacity: 1)
let struct_memory = struct_pointer.pointee
struct_pointer.deallocate()
return struct_memory
}
func enableRawMode(fileHandle: FileHandle) -> termios {
var raw: termios = initStruct()
View ChuckArrayBasedOnProperty.swift
struct T {
let s: String
let v: Int
}
let a = [T(s: "abc", v: 0), T(s: "abc", v: 1), T(s: "def", v: 0)]
let b = Array(a.reduce([Int: [T]]()) { (d, a) -> [Int: [T]] in
var d = d
let t = a.v
@Que20
Que20 / EnumBinaryTree.swift
Created Dec 7, 2020
An enum based BinaryTree implementation.
View EnumBinaryTree.swift
enum BinaryTree<Element> {
case leaf
indirect case node(Element, l: BinaryTree<Element>, r: BinaryTree<Element>)
}
extension BinaryTree {
init(_ value: Element) {
self = .node(value, l: .leaf, r: .leaf)
}
}
@Que20
Que20 / PagerViewController.swift
Created Dec 7, 2020
A simple paged view controller implementation.
View PagerViewController.swift
import Foundation
import UIKit
protocol PagerViewControllerDelegate: class {
func pagerViewController(controller: PagerViewController,
didUpdatePageCount count: Int)
func pagerViewController(controller: PagerViewController,
didUpdatePageIndex index: Int)
}
@Que20
Que20 / sortedObject.swift
Created Jul 23, 2019
Sorted array of objects.
View sortedObject.swift
struct A {
var v: Bool
var s: String
}
var arr = [A(v: false, s: "asd"), A(v: true, s: "zxc"), A(v: true, s: "sdf")]
arr = arr.sorted(by: { $0.v && !$1.v })
print(arr)
@Que20
Que20 / imageDarkness.swift
Created Jul 23, 2019
Check if an image is dark in Swift.
View imageDarkness.swift
func imageIsDark(image: CGImage) -> Bool {
let redLum = 0.299
let greenLum = 0.578
let blueLum = 0.114
let maxLum = 150.0
guard let imageData = image.dataProvider?.data else { return false }
guard let ptr = CFDataGetBytePtr(imageData) else { return false }
let length = CFDataGetLength(imageData)
let threshold = Int(Double(image.width * image.height) * 0.45)
var darkPixels = 0
@Que20
Que20 / dataStructures.Swift
Created Feb 26, 2016
Swift Data Structures
View dataStructures.Swift
// Stack
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()