Skip to content

Instantly share code, notes, and snippets.

@hlung
hlung / Array+Pairs.swift
Created May 3, 2020 12:21
Iterate through all elements in pair tuples
import Foundation
public extension Array {
// Iterate through all elements in pair tuples
// e.g. [1, 2, 3, 4].allPairs = [(1, 2), (2, 3), (3, 4)]
var allPairs: [(Element, Element)] {
var array: [(Element, Element)] = []
for i in 0..<self.count - 1 {
array.append((self[i], self[i+1]))
}
@hlung
hlung / UIColor+Hex.swift
Created May 3, 2020 12:12
Create UIColor from hex string. e.g. UIColor(hex: "EAEAEA")
import UIKit
public extension UIColor {
convenience init(hex: String) {
let r, g, b, a: CGFloat
var hex = hex
if hex.hasPrefix("#") { hex = String(hex.dropFirst()) }
if hex.count == 6 {
@hlung
hlung / XcodeExtReverseLines.swift
Last active April 21, 2020 03:10
A simple Xcode extension that reverses code on selected lines
import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
// Reverses code on selected lines
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
let lines = invocation.buffer.lines as? [String] ?? []
@State private var showModal = false
var body: some View {
Button(action: { self.showModal.toggle() }) {
HStack {
Text("Show MODAL")
Spacer()
Text("〉")
}
}.sheet(isPresented: $showModal) {
let data = """
{
"response": [
{
"name": "Kitty",
},
{
"name": "Doggy",
}
]
let exampleData = """
[
{
"type": "cat",
"name": "Kitty",
},
{
"type": "dog",
"name": "Doggy",
}
struct LossyArray<Element: Decodable>: Decodable {
private(set) var elements: [Element]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var elements = [Element]()
if let count = container.count {
elements.reserveCapacity(count)
}
struct AnimalContainer: Decodable {
let animal: Animal
enum AnimalType: String, Decodable {
case cat
case dog
}
enum CodingKeys: String, CodingKey {
case type
struct UserSettings: Codable {
let someBool: Bool
let someDate: Date
enum CodingKeys: String, CodingKey {
case someBool = "someDifferentKeyBool"
case someDate = "someDifferentKeyDate"
}
}