Last active
March 4, 2020 11:46
-
-
Save rdv0011/b1fd28e692f40aed5908c38a903d7f6f to your computer and use it in GitHub Desktop.
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
import UIKit | |
// Type erasure example | |
protocol Joint { | |
associatedtype T | |
var count: T { get } | |
} | |
class SingleJoint: Joint { | |
var count: Float { | |
1 | |
} | |
} | |
class MultipleJoints: Joint { | |
var count: Int { | |
10 | |
} | |
} | |
protocol ViewModelProtocol { | |
var joints: String { get } | |
} | |
class ViewModel2<T: Joint> { | |
private let joint: T | |
init(joint: T) { | |
self.joint = joint | |
} | |
} | |
// Here we do type erasing | |
// To be able to assign ViewModel2 instance to a property that confirms to ViewModelProtocol later | |
extension ViewModel2: ViewModelProtocol { | |
var joints: String { | |
"\(joint.count)" | |
} | |
} | |
// Introducing generic types to the view controller is not an option | |
class ViewController: UIViewController { | |
let model: ViewModelProtocol = ViewController.modelInstance() | |
func test() { | |
// Here we refer to a non generic protocol | |
// that delegates a call to a corresponding generic implementation i.e. SingleJoint or MultipleJoints | |
print("Joints \(model.joints)") | |
} | |
} | |
extension ViewController { | |
private static var decisionMakeCondition: Bool { | |
true | |
} | |
// This is where the magic happens | |
// We can return an instance of a generic type assigning it to non generic one | |
private static func modelInstance() -> ViewModelProtocol { | |
if self.decisionMakeCondition { | |
return ViewModel2(joint: SingleJoint()) | |
} else { | |
return ViewModel2(joint: MultipleJoints()) | |
} | |
} | |
} | |
let controller = ViewController() | |
controller.test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment