Skip to content

Instantly share code, notes, and snippets.

@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"
}
}
extension URLSession {
func send<T: Decodable>(_ request: URLRequest,
completion: @escaping ((Result<T, Error>) -> Void)) {
let task = dataTask(with: request) { (data, response, error) in
if let data = data {
do {
let decoded = try JSONDecoder().decode(T.self, from: data)
completion(.success(decoded))
}
catch let error {