Skip to content

Instantly share code, notes, and snippets.

View BasThomas's full-sized avatar

Bas Broek BasThomas

View GitHub Profile
import UIKit
class VC: UIViewController {
func formatter() -> DateFormatter {
struct Formatter {
static let f: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .medium
print("I am called just once")
return f
import Foundation
struct Person: Codable {
public let name: String
}
let person = Person(name: "Bas")
let payload = try JSONEncoder().encode(person)
let string = String(data: payload, encoding: .utf8) // {"name":"Bas"}
let decodedPerson = try JSONDecoder().decode(Person.self, from: payload) // Person(name: "Bas")
@BasThomas
BasThomas / Sequence+Contains.swift
Created March 6, 2018 18:29
A `containsOnly` and `containsNone` implementation for `Sequence`.
import Foundation
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether every element of the sequence
/// is equal to the given element.
func containsOnly(_ element: Element) -> Bool {
var iterator = self.makeIterator()
guard iterator.next() != nil else { return false }
return first(where: { $0 != element }) == nil
@BasThomas
BasThomas / shim-swift-4-1.swift
Last active April 11, 2018 21:53
Backward compatibility for `compactMap` in Swift 4.0.
#if swift(>=4.1)
#else
extension Collection {
func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
struct A: Hashable { }
struct B: Hashable { // error: type 'B' does not conform to protocol 'Hashable'
let aa: [A]
}
@BasThomas
BasThomas / xcode.md
Created September 1, 2018 08:06
Terminal commands
  • defaults write com.apple.dt.Xcode IDEIndexerActivityShowNumericProgress -bool true
// Beware: this is "pseudocode", which is not guaranteed to compile. ;-)
import CoreData
protocol CoreDataProtocol {
var managedObjectContext: NSManagedObjectContext? { get }
}
class Card: NSManagedObject, CoreDataProtocol {
// conforms by default
struct Solution<Problem>: Collection {
struct Step<T> {
let step: T
}
let steps: [Step<Problem>]
var input: Step<Problem> {
return steps.first! // safe, as steps will guaranteed to be larger than 0.
}
struct Vector<T> {
let size: Int
let initialValue: T
struct Position: Equatable {
let row: Int
let column: Int
}
typealias Matrix = [Position]
import Foundation
struct Messages: Decodable {
let count: String
let messages: [Message]
enum CodingKeys: String, CodingKey {
case count = "message-count"
case messages
}