Skip to content

Instantly share code, notes, and snippets.

// Transform the presentation of a Modal VC into a promise.
// This pattern is useful when the modal has to pass some information back to the presenter
func promisifyModal() -> Promise<String> {
return Promise<String>(in: .main) { resolve, _, _ in
let vc = AnimalVC(store: self.store, connected: true, resolve: resolve)
vc.modalPresentationStyle = .overFullScreen
self.present(vc, animated: true, completion: nil)
}
}
// Data structure to hold the title of the UIAlertAction and the value that will resolve the promise
struct AlertCommand<T> {
let title: String
let returnValue: T
}
// Promisified implementation of the userTapDialog function
func userTapDialog() {
_ = presentAlertVC(
title: "Question!",
func userTapDialog {
// Create the alert
let alertControl = UIAlertController(
title: "Question!",
message: "What's your favourite color?",
preferredStyle: .alert
)
// add the red action
// Promisification of asynchronous code:
func downloadUser() -> Promise<User> {
return Promise<User> {
resolve, reject, cancellation in
self.downloadUser() {
user in
resolve(user)
}
}
}
let user = self.downloadUser()
let movies = self.downloadFavouriteMovies(for: user)
let ratings = self.downloadRatings(for: movies)
let friends = self.downloadFriends(for: users)
let friendsMovies = self.downloadMovies(for: friends)
self.presentProfile(for: user, movies: movies, ratings: ratings, friends: friends, movies: movies)
func prepareUserProfile() {
self.downloadUser() { user in
downloadUserMoviesAndFriendDataToPresentProfile(user: user)
}
}
func downloadUserMoviesAndFriendDataToPresentProfile(user: User) {
self.downloadFavouriteMovies(for: user) { movies in
downloadRatingsAndFriendsDataThenPresentProfile(user: user, movies: movies)
}
self.downloadUser() { user in
self.downloadFavouriteMovies(for: user) { movies in
self.downloadRatings(for: movies) { ratings in
self.downloadFriends(for: users) { friends in
self.downloadMovies(for: friends] { friendMovies in
self.presentProfile(
for: user,
movies: movies,
ratings: ratings,
friends: friends,
let operationQueue = OperationQueue()
operationQueue.addOperation {
// asynchronous task that will be executed somewhen in the future
}
/// Protocol that defines the entities in our database.
/// They must have an identifier that is used to retrieve them.
protocol Entity {
/// The identifier of the resource
var id: String { get }
}
extension Entity {
/// Helper to retrieve the table name from the Type of the entity.
static var tableName: String { return String(reflecting: Self.self) }
/// Protocol that defines the entities in our database.
/// They must have an identifier that is used to retrieve them.
protocol Entity {
/// The identifier of the resource
var id: String { get }
}
extension Entity {
/// Helper to retrieve the table name from the Type of the entity.
static var tableName: String { return String(reflecting: Self.self) }