Skip to content

Instantly share code, notes, and snippets.

View idrougge's full-sized avatar

Iggy Drougge idrougge

  • Stockholm, Sweden
View GitHub Profile
extension Sequence {
func sorted<T>(by kp: KeyPath<Element, T>) -> [Element] where T: Comparable {
self.sorted {
$0[keyPath: kp] < $1[keyPath: kp]
}
}
}
enum Either<Left, Right> {
case left(Left)
case right(Right)
}
extension Either: Decodable where Left: Decodable, Right: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
@idrougge
idrougge / Non-matching-IUO.swift
Created November 11, 2019 18:44
IUO is not Optional
protocol Countable {
var count: Int? {get}
}
struct OptionalCount: Countable {
var count: Int? = 0
}
struct DeadlyCount: Countable { // Type 'DeadlyCount' does not conform to protocol 'Countable'
var count: Int! = 0 // 1. Candidate has non-matching type 'Int?' <----------
@idrougge
idrougge / Protocol.Type.swift
Created November 11, 2019 15:10
Protocol existential crisis
protocol P {}
struct A: P {}
struct B: P {}
struct C: P {}
var someP: P.Type = A.self
someP == A.self // true
someP == B.self // false
switch someP {
@idrougge
idrougge / UILabel+hyphenation.swift
Last active March 8, 2019 15:40
Turn on hyphenation for UILabel
extension UILabel {
func hyphenate() {
let paragraphStyle = NSMutableParagraphStyle()
let attstr = NSMutableAttributedString(attributedString: self.attributedText!)
paragraphStyle.hyphenationFactor = 1.0
attstr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(0..<attstr.length))
self.attributedText = attstr
}
}
@idrougge
idrougge / UILabel+smallestWidth.swift
Last active December 21, 2017 15:58
Calculate minimum width for UILabel for better headlines
extension UILabel {
/// Minimum width fitting text in alotted number of lines
var minimumWidth:CGFloat {
get {
guard intrinsicContentSize.width >= bounds.width || intrinsicContentSize.height >= ceil(font.lineHeight) * CGFloat(numberOfLines)
else { return intrinsicContentSize.width }
let rect = self.textRect(forBounds: CGRect.init(origin: .zero, size: CGSize(width: bounds.width, height: .infinity)), limitedToNumberOfLines: self.numberOfLines)
return calculateWidth(0 ..< rect.width, height: rect.height)
}