Skip to content

Instantly share code, notes, and snippets.

@dfelber
dfelber / BouncyButton.swift
Last active May 8, 2022 05:38
Bouncy UIButton in swift. Becomes small when pressed and restores its size when released. Swift 3
//
// BouncyButton.swift
//
// Created by Domink Felber on 20.03.16.
// Copyright © 2016 Domink Felber. All rights reserved.
//
import Foundation
import UIKit
public extension Sequence {
func categorise<U : Hashable>(_ key: (Iterator.Element) -> U) -> [U:Int] {
var dict: [U:Int] = [:]
self.forEach { el in
let key = key(el)
dict[key] = (dict[key] ?? 0) + 1
}
return dict
@dfelber
dfelber / CGRect+center.swift
Created October 28, 2016 06:29
Swift extension for CGRect to return the center as a CGPoint.
extension CGRect {
var center: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
extension String {
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
@dfelber
dfelber / HTTPStatusCodes.swift
Created September 7, 2016 12:19
Enum of HTTP Status codes
enum StatusCode: Int {
// Informational
case Continue = 100
case SwitchingProtocols = 101
case Processing = 102
// Success
case OK = 200
case Created = 201
case Accepted = 202
@dfelber
dfelber / UIEdgeInsets+Uniform.swift
Created September 5, 2016 15:29
Initializer for UIEdgeInsets with one value for top, bottom, left and right
extension UIEdgeInsets {
init(inset: CGFloat) {
self.top = inset
self.bottom = inset
self.left = inset
self.right = inset
}
}
@dfelber
dfelber / Array+RandomValue.swift
Last active September 2, 2016 07:01
Returns a random value from an array
extension Array {
func randomValue() -> Element? {
guard self.isEmpty == false else {
return nil
}
let idx = Int(arc4random() % UInt32(count))
return self[idx]
}
}
@dfelber
dfelber / NSDate+Comparable.swift
Last active August 26, 2016 06:58
Compare NSDate with comparison operators
public func <(a: NSDate, b: NSDate) -> Bool {
return a.compare(b) == NSComparisonResult.OrderedAscending
}
public func >(a: NSDate, b: NSDate) -> Bool {
return a.compare(b) == NSComparisonResult.OrderedDescending
}
@dfelber
dfelber / CarrierInfo.swift
Created June 14, 2016 14:53
Get carrier info from your iOS Device
import CoreTelephony
let info: CTTelephonyNetworkInfo = CTTelephonyNetworkInfo()
guard let carrier: CTCarrier = info.subscriberCellularProvider else {
// No carrier info available
return
}
print(carrier.carrierName)
print(carrier.mobileCountryCode)
@dfelber
dfelber / Color+Hex.swift
Last active August 6, 2021 10:05
Extension for UIColor and NSColor to initialize them with hexadecimal values like `0xcf0b69`
#if os(OSX)
import AppKit
typealias Color = NSColor
#elseif os(iOS) || os(tvOS)
import UIKit
typealias Color = UIColor
#endif
extension Color