Skip to content

Instantly share code, notes, and snippets.

@ole
ole / FontsPlayground.swift
Last active October 7, 2016 14:45
Fonts with monospaced (tabular) digits
// Adopted from: http://stackoverflow.com/a/19976535/116862 by http://stackoverflow.com/users/2547229/benjohn.
import PlaygroundSupport
import UIKit
let baseFont = UIFont.preferredFont(forTextStyle: .body)
let baseDescriptor = baseFont.fontDescriptor
let proportionalFeatures = [
[
@ole
ole / NextDate.swift
Last active December 12, 2016 12:32
Paste into a playground in Xcode 8.
// macOS 10.12.1 or iOS 10, Swift 3.0.1
import Foundation
var calendar = Calendar(identifier: .gregorian)
// GMT+1 (GMT+2 under daylight saving)
calendar.timeZone = TimeZone(identifier: "Europe/Berlin")!
// 2016-10-30 02:30:00 +02:00
// Europe/Berlin switched from daylight saving to winter time on this date, i.e. on 2016-10-30 03:00:00 +02:00 the clock was moved back by one hour.
@ole
ole / SortedArray.swift
Created January 23, 2017 18:22
An array that keeps its elements sorted at all times.
/// An array that keeps its elements sorted at all times.
public struct SortedArray<Element> {
// Not sure if it's a good idea to use `ArraySlice` as the backing store. It lets me make SortedArray.SubSequence == SortedArray, but the price you pay for that is that one small slice, if stored permanently and not just locally inside a function, can easily retain a much larger collection, and this is hard to notice by the developer.
fileprivate var _elements: ArraySlice<Element>
public typealias Comparator<A> = (A, A) -> Bool
/// The predicate that determines the array's sort order.
fileprivate let areInIncreasingOrder: Comparator<Element>
@ole
ole / MeasurementParsing.swift
Last active January 27, 2017 18:04
Parse measurement expressions like `"5 m²"` and convert them into `Measurement` values. Uses the Objective-C runtime to find the known and valid symbols for a given unit (such as `UnitArea`). Adopts `ExpressibleByStringLiteral` for easy initialization.
// Parse measurement expressions like `"5 m²"` and convert them into `Measurement` values.
// Uses the Objective-C runtime to find the known and valid symbols for a given unit
// (such as `UnitArea`). Adopts `ExpressibleByStringLiteral` for easy initialization.
import ObjectiveC
enum ObjectiveCRuntime {
class Class {
let base: AnyClass
@ole
ole / fun-with-string-interpolation.swift
Last active June 13, 2018 15:02
Fun with String Interpolation — For more information read my article at https://oleb.net/blog/2017/01/fun-with-string-interpolation/. — Dependencies: Foundation
/// An unescaped string from a potentially unsafe
/// source (such as user input)
struct UnsafeString {
var value: String
}
/// A string that either comes from a safe source
/// (e.g. a string literal in the source code)
/// or has been escaped.
struct SanitizedHTML {
let str = "👨🏾‍🚒"
print(str.unicodeScalars.map { "0x\(String($0.value, radix: 16))" })
// → ["0x1f468", "0x1f3fe", "0x200d", "0x1f692"]
print(str.utf16.map { "0x\(String($0, radix: 16))" })
// → ["0xd83d", "0xdc68", "0xd83c", "0xdffe", "0x200d", "0xd83d", "0xde92"]
print(str.utf16.count)
// → 7
let utf16Offset = 2
@ole
ole / type-pattern-matching.swift
Last active October 12, 2017 16:51
Pattern matching for types. See https://twitter.com/Gernot/status/918490645118976000 for context.
func ~= <T, U> (pattern: T.Type, value: U.Type) -> Bool {
return pattern == value
}
func f<T>(_ type: T.Type) {
switch T.self {
case Int.self:
print("Int")
default:
print("Something else")
Process: Notes [17745]
Path: /Applications/Notes.app/Contents/MacOS/Notes
Identifier: com.apple.Notes
Version: 4.5 (863)
Build Info: Notes-863000000000000~1
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: Notes [17745]
User ID: 501
let s = "Hello World"
let evenIndices = s.indices.enumerated()
.filter { $0.offset % 2 == 0 }
.map { $0.element }
for idx in evenIndices {
print(s[idx])
}
@ole
ole / URLSession.swift
Created February 22, 2018 00:08
Paste this into a playground and let it run for 5 seconds. You’ll get a non-nil response *and* error.
import Foundation
import PlaygroundSupport
let bigFile = URL(string: "https://speed.hetzner.de/1GB.bin")!
let task = URLSession.shared.dataTask(with: bigFile) { (data, response, error) in
print("data: \(data)")
print("response: \(response)")
print("error: \(error)")
}
task.resume()