Skip to content

Instantly share code, notes, and snippets.

View jimmythai's full-sized avatar

Atsushi Yamamoto jimmythai

View GitHub Profile
@jimmythai
jimmythai / Throttler.swift
Last active April 21, 2019 12:00
Use case: To prevent button from being tapped multiple times
class Throttler {
private var workItem: DispatchWorkItem?
private var previousRun: Date = .distantPast
private let queue: DispatchQueue
private let minimumDelay: TimeInterval
init(minimumDelay: TimeInterval, queue: DispatchQueue = .main) {
self.minimumDelay = minimumDelay
self.queue = queue
}
extension Data {
var hexadecimalString: String {
return self.map { String(format: "%02.2hhx", $0) }.joined()
}
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
let isDisabledAction = action == #selector(copy(_:)) || action == #selector(cut(_:)) || action == #selector(paste(_:))
return isDisabledAction ? false : super.canPerformAction(action, withSender: sender)
}
import UIKit
import RxSwift
import RxCocoa
extension Reactive where Base: UISearchController {
var searchResultUpdater: DelegateProxy<UISearchController, UISearchResultsUpdating> {
return RxSearchResultUpdatingProxy.proxy(for: base)
}
var queryText: Observable<String> {
// In SomeTableViewCell.swift
class SomeTableViewCell: UITableViewCell, Reusable {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder: ) has not been implemented")
}
}
extension UITableView {
// For `register` methods
func register<T: Reusable>(_ reusableClass: T.Type) where T: UITableViewCell {
register(reusableClass, forCellReuseIdentifier: reusableClass.reusableIdentifier)
}
func register<T: NibReusable>(_ nibReusableClass: T.Type) where T: UITableViewCell {
register(nibReusableClass.nib, forCellReuseIdentifier: nibReusableClass.reusableIdentifier)
}
protocol Reusable: class {
static var reusableIdentifier: String { get }
}
extension Reusable {
static var reusableIdentifier: String {
return String(describing: self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(SomeTableViewCell.self, bundle: nil), forCellReuseIdentifier: "\(SomeTableViewCell.self)")
// tableView.register(UINib(nibName: "\(SomeTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(SomeTableViewCell.self)")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(SomeTableViewCell.self, for: indexPath) as! SomeTableViewCell
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SomeCell", for: indexPath) as! SomeTableViewCell
return cell
}
// If rawValue is `Int`...
enum FizzBuzz: Int {
case fizz
case buzz
static let count: Int = {
var count = 0
while let _ = FizzBuzz(rawValue: max) { count += 1 }
return count
}()