RBGA Image - Swift

public struct Pixel {
    public var value: UInt32
    
    public var red: UInt8 {
        get {
            return UInt8(value & 0xFF)
        }
        set {
            value = UInt32(newValue) | (value & 0xFFFFFF00)
        }
    }
    
    public var green: UInt8 {
        get {
            return UInt8((value >> 8) & 0xFF)
        }
        set {
            value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF)
        }
    }
    
    public var blue: UInt8 {
        get {
            return UInt8((value >> 16) & 0xFF)
        }
        set {
            value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF)
        }
    }
    
    public var alpha: UInt8 {
        get {
            return UInt8((value >> 24) & 0xFF)
        }
        set {
            value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF)
        }
    }
}

public class RGBAImage {
    public var pixels: UnsafeMutableBufferPointer<Pixel>
    
    public let width: Int
    public let height: Int
    
    public init?(image: UIImage) {
        guard let cgImage = image.cgImage else {
            print("Unable to get cgImage")
            return nil
        }
        
        width = cgImage.width
        height = cgImage.height
        
        let colorSpace       = CGColorSpaceCreateDeviceRGB()
        let bytesPerPixel    = 4
        let bitsPerComponent = 8
        let bytesPerRow      = bytesPerPixel * width
        let bitmapInfo       = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
        
        let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height)
        
        guard let imageContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("Cannot create context")
            return nil
        }
        imageContext.draw(cgImage, in: CGRect.init(x: 0, y: 0, width: width, height: height))
        
        pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)
    }
    
    public func toUIImage() -> UIImage? {
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
        bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
        
        let bytesPerRow = width * 4
        
        guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else {return nil}
        
        guard let cgImage = imageContext.makeImage() else {return nil}
        let image = UIImage(cgImage: cgImage)
        
        return image
    }
    
    deinit {
        pixels.deallocate()
    }
}

This "bit" of code retrieves all the pixels from an image, the pixels can then be changed and converted back to an UIImage.

KeyedDecodingContainer - Swift

public extension KeyedDecodingContainer {
    func decodeWrapper<T: Decodable>(key: K) -> T? {
        do {
            return try decodeIfPresent(T.self, forKey: key) ?? nil
        } catch {
            print(error)
            return nil
        }
    }

    func decodeWrapperArray<T: Decodable>(key: K) -> [T]? {
        do {
            return try decodeIfPresent([T].self, forKey: key)
        } catch {
            print(error)
            return nil
        }
    }
}

// Example 
struct Person: Codable {
    let id: Int?
    let name: String?
    
    enum CodingKeys: String, CodingKey {
        case id, name
    }
}

// From
extension Person: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try values.decode(Int.self, forKey: .id)
        self.name = try values.decode(String.self, forKey: .name)
    }
}

//To
extension Person: Decodable {
    init(from coder: Decoder) throws {
        let container = try coder.container(keyedBy: CodingKeys.self)
        self.id = container.decodeWrapper(key: .id)
        self.name = container.decodeWrapper(key: .name)
    }
}

KeyedDecodingContainer extension that makes it easier to decode. Instead of having to try retrieve each value, the wrapper returns nil if not found. The new function also checks if the key is present, so less writing each checking each time.

UIControl Analytics - Swift

import UIKit

public class ClosureSleeve {
    public let closure: () -> Void
    public let analyticsKey: String?
    
    public init (_ key: String?, closure: @escaping () -> Void) {
        self.analyticsKey = key
        self.closure = closure
    }
    
    @objc public func invoke () {
        closure()
        if let key = self.analyticsKey {
            // Track analytics
        }
    }
}

extension UIControl {
    
    func addAction(for controlEvents: UIControl.Event, analyticsIdentifier: String? = nil, _ closure: @escaping () -> Void ) {
        let sleeve = ClosureSleeve(analyticsIdentifier, closure: closure)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
        objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

//Example
let button = UIButton(frame: .zero)
button.addAction(for: .touchUpInside, analyticsIdentifier: "Button name") { [weak self] in
    // Do whatever you wish
})

Color Extension - Swift

extension UIColor {
    var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        return (red, green, blue, alpha)
    }
    
    var alpha: CGFloat? {
        return self.rgba.alpha
    }
    
    var red: CGFloat? {
        return self.rgba.red
    }
    
    var green: CGFloat? {
        return self.rgba.green
    }
    
    var blue: CGFloat? {
        return self.rgba.blue
    }
}

Easy extension to get the colour components or each one individually.

Date extension - Swift

public extension Date {
    var weekday: Int {
        return Calendar.current.component(.weekday, from: self)
    }
    
    var day: Int {
        return Calendar.current.component(.day, from: self)
    }
    
    var minute: Int {
        return Calendar.current.component(.minute, from: self)
    }
    
    var hour: Int {
        return Calendar.current.component(.hour, from: self)
    }
    
    var second: Int {
        return Calendar.current.component(.second, from: self)
    }
    
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
    
    var year: Int {
        return Calendar.current.component(.year, from: self)
    }
}

UIControl - Swift

import UIKit

public class ClosureSleeve {
    public let closure: ()->()
    
    public init (_ closure: @escaping ()->()) {
        self.closure = closure
    }
    
    @objc public func invoke () {
        closure()
    }
}

public extension UIControl {
    public func addAction(for controlEvents: UIControl.Event, _ closure: @escaping ()->()) {
        let sleeve = ClosureSleeve(closure)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
        objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

//Example
let button = UIButton(frame: .zero)
button.addAction(for: .touchUpInside, {
    // Do whatever you wish
})