Skip to content

Instantly share code, notes, and snippets.

View efremidze's full-sized avatar
👨‍💻

Lasha Efremidze efremidze

👨‍💻
View GitHub Profile
extension UserDefaults {
func set(forEvery: Int, for key: String, onChange: () -> Void) {
let count = integer(forKey: key) % forEvery
if count == 0 { onChange() }
set(count + 1, forKey: key)
}
}
import ObjectiveC.runtime
// https://codelle.com/blog/2016/2/calling-methods-from-strings-in-swift/
func extractMethod(_ owner: AnyObject, _ selector: Selector) -> ((Any?, Any?) -> AnyObject)? {
guard let method = getMethod(owner, selector) else { return nil }
let imp = method_getImplementation(method)
typealias CFunction = @convention(c) (AnyObject, Selector, Any?, Any?) -> Unmanaged<AnyObject>
let function = unsafeBitCast(imp, to: CFunction.self)
return { arg1, arg2 in function(owner, selector, arg1, arg2).takeUnretainedValue() }
}
extension UIView {
func toType<T: UIView>(of type: T.Type) -> T {
guard let value = self as? T else {
fatalError("Cannot convert value of type `\(type(of: self))` to expected type `\(type)`")
}
return value
}
}
extension UILayoutPriority {
static func +(lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
return UILayoutPriority(lhs.rawValue + rhs)
}
static func -(lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
return UILayoutPriority(lhs.rawValue - rhs)
}
}
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
public class ContainerView<V: UIView>: UIView {
private var topConstraint: NSLayoutConstraint!
private var bottomConstraint: NSLayoutConstraint!
private var leftConstraint: NSLayoutConstraint!
private var rightConstraint: NSLayoutConstraint!
/// The view inside the container.
public let contentView: V
extension NSLock {
func withCriticalScope<T>(block: (Void) -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
class Cell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
private static var sharedInstance: Cell!
static func makeCell(width: CGFloat) -> Cell {
if sharedInstance == nil {
sharedInstance = UINib(nibName: String(describing: Cell.self)).instantiate(withOwner: nil, options: nil).first as! Cell
sharedInstance.constrain { [$0.imageView.widthAnchor.constraint(equalToConstant: width)] }
}
return sharedInstance
}
extension Array where Element : Equatable {
mutating func remove(_ element: Element) -> Element? {
return index(of: element).map { remove(at: $0) }
}
}
protocol XibViewProtocol {}
extension XibViewProtocol where Self: UIView {
static func nib(_ name: String? = nil, owner: Any? = nil, bundle: Bundle = .framework) -> Self {
return bundle.loadNibNamed(name ?? String(describing: self), owner: owner, options: nil)!.first as! Self
}
}
extension UIView: XibViewProtocol {}