Created
May 6, 2016 00:09
-
-
Save hectormatos2011/f20bdd4db779e3698a6568ff25de72fb to your computer and use it in GitHub Desktop.
Using type erasure to replace Objective-C's UIView<SomeProtocol> property feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
protocol MythicalCreatureDisplayable: class { | |
associatedtype Conformer = Self | |
var displayer: Conformer { get } | |
func displayMythicalCreature() | |
} | |
final class KrakenView: UIView, MythicalCreatureDisplayable { | |
func displayMythicalCreature() { | |
print("draw a Kraken") | |
} | |
} | |
extension MythicalCreatureDisplayable where Self: UIView { | |
var displayer: UIView { return self } | |
} | |
private extension MythicalCreatureDisplayable { | |
func getDisplayer() -> Conformer { | |
return displayer | |
} | |
} | |
final class AnyMythicalTypeDisplayable<T>: MythicalCreatureDisplayable { | |
var displayer: T { return _getDisplayer() } | |
private let _getDisplayer: () -> T | |
private let _displayMythicalCreature: () -> Void | |
required init<U: MythicalCreatureDisplayable where U.Conformer == T>(_ displayable: U) { | |
_getDisplayer = displayable.getDisplayer | |
_displayMythicalCreature = displayable.displayMythicalCreature | |
} | |
func displayMythicalCreature() { | |
_displayMythicalCreature() | |
} | |
} | |
let krakenView = KrakenView() | |
let regularView = UIView() | |
var mythicalDisplayableView: AnyMythicalTypeDisplayable<UIView> | |
mythicalDisplayableView = AnyMythicalTypeDisplayable(krakenView) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment