Skip to content

Instantly share code, notes, and snippets.

View efremidze's full-sized avatar
👨‍💻

Lasha Efremidze efremidze

👨‍💻
View GitHub Profile
extension Array {
subscript(safe index: Int, repeated repeated: Bool) -> Element? {
return isEmpty ? nil : self[index % count]
}
}
protocol Storable {}
extension Storable {
var storedValue: Any? {
get { return UserDefaults.standard["value"] }
nonmutating set { UserDefaults.standard["value"] = newValue }
}
}
struct Storage: Storable {}
let storage = Storage()
storage.storedValue = "🐼"
@efremidze
efremidze / superview.swift
Last active March 12, 2017 01:08
find superview of given type
extension UIView {
func superview<T>(of type: T.Type) -> T? {
return superview as? T ?? superview.flatMap { $0.superview(of: T.self) }
}
}
@efremidze
efremidze / random.swift
Last active March 12, 2017 01:08
random number from range
extension UInt32 {
static func random(_ range: Range<UInt32>) -> UInt32 {
return arc4random_uniform(range.upperBound - range.lowerBound) + range.lowerBound
}
}
extension CGFloat {
@efremidze
efremidze / flatten.swift
Last active March 12, 2017 01:08
2d array extension
extension Array where Element: _ArrayType, Element.Generator.Element: AnyObject? {
func flatten() {
return flatMap { $0.flatMap { $0 } }
}
}
@efremidze
efremidze / unwrap.swift
Last active March 12, 2017 01:09
unwrap shortcut
extension Optional {
func unwrap(_ f: (Wrapped) -> Void) {
_ = self.map(f)
}
}
// usage:
// let username: String?
@efremidze
efremidze / init.swift
Last active March 12, 2017 01:12
init
@warn_unused_result
func Init<T>(value: T, @noescape block: (object: T) -> Void) -> T {
block(object: value)
return value
}
@efremidze
efremidze / propertyNames.swift
Last active March 12, 2017 01:12
List of class's properties
func propertyNames(forClass: AnyClass) -> [String] {
var count = UInt32()
let properties = class_copyPropertyList(forClass, &count)
let names: [String] = (0..<Int(count)).flatMap { i in
let property: objc_property_t = properties[i]
guard let name = NSString(UTF8String: property_getName(property)) as? String else {
debugPrint("Couldn't unwrap property name for \(property)")
return nil
}
return name
@efremidze
efremidze / CABasicAnimationFromValue.swift
Last active March 12, 2017 01:12
CABasicAnimation with `keyPath` value set to `fromValue`
// MARK: - CABasicAnimation
extension CABasicAnimation {
/// Creates a new animation object with its `keyPath` property set to `path` and current `keyPath` value set to `fromValue`.
convenience init(keyPath path: String, layer: CALayer) {
self.init(keyPath: path)
self.fromValue = layer.presentation()?.value(forKeyPath: path)
}
}
extension UIFont {
func bold() -> UIFont? {
return fontDescriptor.withSymbolicTraits(.traitBold).map { UIFont(descriptor: $0, size: 0) }
}
}