Skip to content

Instantly share code, notes, and snippets.

View PresentViewContainerVC.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = StarsViewTestVC()
window!.rootViewController = vc
return true
}
View FakeAsyncService.swift
protocol ThingsService {
func getThings(onCompletion callback: (Result<[Thing]>) -> Void)
func add(onCompletion callback: (Result<Bool>) -> Void)
}
class FakeThingsService: ThingsService {
private(set) var things: [Thing]
init(things: [Thing]) {
self.things = things
View ResultWithDelegate.swift
protocol ThingsServiceDelegate {
func service(_ ThingsService, didFinishWithResult: Result<[Thing]>)
}
class ThingsService {
private var delegate: ThingsServiceDelegate
init(with delegate: ThingsServiceDelegate) {
self.delegate = delegate
}
View ResultWithCallback.swift
func getThings(onCompletion callback: (Result<[Thing]>) -> Void) { ... }
View ResultWithMonad.swift
let successResult: Result<[Thing]> = .success([aThing, anotherThing])
let failureResult: Result<[Thing]> = .failure(Error(...))
View ResultAsOptionals.swift
let successResult: ([Thing]?, Error?) = ([aThing, anotherThing], nil)
let failureResult: ([Thing]?, Error?) = (nil, Error(...))
View URLSession+SyncRequest.swift
extension URLSession {
func sendSynchronousRequest(request: URLRequest) -> (Data?, URLResponse?, Error?) {
let semaphore = DispatchSemaphore(value: 0)
var result: (data: Data?, response: URLResponse?, error: Error?)
let task = self.dataTask(with: request) {
result = (data: $0, response: $1, error: $2)
semaphore.signal()
}
task.resume()
View FakeSyncServices.swift
protocol ThingsService {
func getThings() -> Result<[Thing]>
func add(thing: Thing) -> Result<Bool>
}
class FakeThingsService: ThingsService {
private(set) var things: [Thing]
init(things: [Thing]) {
self.things = things
}
View TestingServices.swift
class ServicesTest: XCTestCase {
let service = ProfileService()
setup() {
// handle authentication if needed
// let authService = ...
// let authMethod = ...
// authService.auth(authMethod)
}
View ComposingSyncServices.swift
func startApp() {
onMainDo({
self.activityIndicator.startAnimating()
}, onBackgroundDo: {
let storage = PersistentSecureStorage.shared()
guard let savedToken == storage.token {
return .goToAuth
}
let tokenIsValid = authService.isValidToken(savedToken)
if !tokenIsValid {