Skip to content

Instantly share code, notes, and snippets.

Shared code that exists in framework

@objc public protocol Sound {
	@objc optional func woo()
}

public class Foo: NSObject, Sound {
  func action() {
 ((self as Sound).woo ?? default_woo)() // calls `woo` method if available or defaults to default_woo method
@wh1pch81n
wh1pch81n / UnitTestSharedINFramework.swift
Created March 7, 2017 04:08
What if you want to put some common unit test code in a framework? By default, you can not. However if you create protocols for XCTestCase and company, you can.
// Framework code
public protocol _XCTestCaseProtocol: NSObjectProtocol {
func _expectation(description: String) -> _XCTestExpectationProtocol
}
public protocol _XCTestExpectationProtocol {
func fulfill()
}
extension _XCTestCaseProtocol {
public func _expectation(description: String) -> _XCTestExpectationProtocol {
@wh1pch81n
wh1pch81n / UIAlertController.swift
Created March 2, 2017 04:17
A helper method that will tap one of the buttons programmatically.
// Source: http://stackoverflow.com/a/40634752/3400034
extension UIAlertController {
func tapButton(at index: Int, animated: Bool) {
guard Thread.isMainThread else {
DispatchQueue.main.async {
self.tapButton(at: index, animated: animated)
}
return
}
enum Planets: String {
case Mercury
case Venus
case Earth
}
// Add protocol to enums that need it
public protocol UsesRawValue {
var rawValue: String { get }
}
@wh1pch81n
wh1pch81n / 1.swift
Last active February 18, 2017 16:54
// An enum of some planets
enum Planets: String {
case Mercury
case Venus
case Earth
}
// This extension will allow us to use string enums without
// explicitly calling rawValue to get the string
extension Dictionary where Key: ExpressibleByStringLiteral {
my_viewcontroller.customizerObject = SpecialRed()
my_viewController.customizerObject = SpecialBlue()
// SWIFT
class SpecialRed: SpecialProtocol<ViewController> {
override func specialMethod(_ viewController: ViewController) {
// customization
}
}
// Objective-C
@interface SpecialBlue: SpecialProtocol<ViewController *>
@end
class ViewController: UIViewController {
var customizerObject: SpecialProtocol<ViewController>?
override func viewDidLoad() {
super.viewDidLoad()
specialMethod()
}
@interface SpecialProtocol <
__covariant VIEW_CONTROLLER: UIViewController *
> : NSObject
- (void)specialMethod:(VIEW_CONTROLLER _Nonnull)viewController;
@end
protocol SpecialProtocol: class {
func specialMethod(_ vc: ViewController)
}
class VCCustomizer: NSObject, SpecialProtocol {
func specialMethod(_ vc: ViewController) {
// Special implementation
}
}