Skip to content

Instantly share code, notes, and snippets.

@wh1pch81n
wh1pch81n / concatenating_errors.swift
Last active January 7, 2017 17:28
What is one trick you can do to avoid the do-catch pyramid of doom? you can return "try method()"
enum ErrorEnum: Error {
case FooError
case BarError
}
func bar(success: Bool) throws -> String {
if success {
return "bar success"
}
throw ErrorEnum.BarError
@wh1pch81n
wh1pch81n / enumstring_as_class.swift
Created January 7, 2017 19:33
NS_ENUM_STRING ports a struct with static strings. This means between objc and swift you have to learn how to read both versions of it which can be confusing. It is much better to have a more consistent api between both. Therefore you can use a class.
func ==(lhs: EnumString, rhs: String) -> Bool {
return lhs.isEqual(rhs)
}
func ==(lhs: String, rhs: EnumString) -> Bool {
return rhs.isEqual(lhs)
}
class EnumString: NSObject {
let rawValue: String
@wh1pch81n
wh1pch81n / programmaticallyTap.swift
Created February 9, 2017 02:22
A little extension that lets you "tap" a UIBarButtonItem programmatically
extension UIBarButtonItem {
public func programmaticallyTap() {
if let target = target
, let action = action
{
target.value(forKey: NSStringFromSelector(action))
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
specialMethod()
}
func specialMethod() {
// overridable method
class ViewController: UIViewController {
var customizerObject: SpecialProtocol?
override func viewDidLoad() {
super.viewDidLoad()
specialMethod()
}
protocol SpecialProtocol: class {
func specialMethod(_ vc: ViewController)
}
class VCCustomizer: NSObject, SpecialProtocol {
func specialMethod(_ vc: ViewController) {
// Special implementation
}
}
@interface SpecialProtocol <
__covariant VIEW_CONTROLLER: UIViewController *
> : NSObject
- (void)specialMethod:(VIEW_CONTROLLER _Nonnull)viewController;
@end
class ViewController: UIViewController {
var customizerObject: SpecialProtocol<ViewController>?
override func viewDidLoad() {
super.viewDidLoad()
specialMethod()
}
// SWIFT
class SpecialRed: SpecialProtocol<ViewController> {
override func specialMethod(_ viewController: ViewController) {
// customization
}
}
// Objective-C
@interface SpecialBlue: SpecialProtocol<ViewController *>
@end
my_viewcontroller.customizerObject = SpecialRed()
my_viewController.customizerObject = SpecialBlue()