Skip to content

Instantly share code, notes, and snippets.

@albertodebortoli
Last active January 28, 2018 17:36
Show Gist options
  • Save albertodebortoli/4729d8b837e6ff4321589049d8f42731 to your computer and use it in GitHub Desktop.
Save albertodebortoli/4729d8b837e6ff4321589049d8f42731 to your computer and use it in GitHub Desktop.
Playing around w/ protocols in Swift
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
import UIKit
protocol HomeViewControllerProtocol: class {
func render()
}
class HomeViewController_1: UIViewController, HomeViewControllerProtocol {
func render() { print("1") }
}
class HomeViewController_2: UIViewController, HomeViewControllerProtocol {
func render() { print("2") }
}
typealias HomeViewController = UIViewController & HomeViewControllerProtocol // πŸ‘ˆπŸ‘ˆπŸ‘ˆ
class Factory {
func home() -> HomeViewController {
return HomeViewController_1()
}
}
let obj = Factory().home()
obj.render() //this is ok
obj.title = "sadfasfa" //this is also ok
// or via extension
protocol P {
func title_ext() -> String?
}
extension UIViewController: P {
func title_ext() -> String? {
return title
}
func somethingElse() -> String? {
return title
}
}
class HomeViewController_3: UIViewController { }
class HomeViewController_4: UIViewController { }
typealias ControllerAndP = UIViewController & P // πŸ‘ˆπŸ‘ˆπŸ‘ˆ
class Factory2 {
func homeVC() -> UIViewController {
return HomeViewController_3()
}
func homeVCAndP() -> ControllerAndP {
return HomeViewController_3()
}
}
let obj2 = Factory2().homeVC()
obj2.title_ext() //this is ok
obj2.title = "sadfasfa" //this is also ok
obj2.somethingElse()
let obj3 = Factory2().homeVCAndP()
obj3.title_ext() //this is ok
obj3.title = "sadfasfa" //this is also ok
obj3.somethingElse()
// Error management
public protocol DialogPresentation {
func showError(title: String, message: String)
}
extension UIView: DialogPresentation {
func showError(title: String, message: String) {
// ...
}
}
extension UIViewController: DialogPresentation {
func showError(title: String, message: String) {
// ...
}
}
// cannot do directly an extension of DialogPresentation,
// need to use `Self: DialogPresentation`, so that the extension applies to UIView and UIViewController.
// It's tricky at first.
// This means I need to create an extra protocol (ShowError) that will be extended with such clause
// also need to create the extensions for the classes that I want the common implementation
public protocol ShowError {
func show(error: NSError)
}
extension UIView: ShowError { }
extension UIViewController: ShowError { }
extension ShowError where Self: DialogPresentation {
public func show(error: NSError) {
// ...
self.showError(title: title, message: message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment