Skip to content

Instantly share code, notes, and snippets.

@mr-v
Created March 7, 2016 17:04
Show Gist options
  • Save mr-v/13657584e3f9ed9e65f6 to your computer and use it in GitHub Desktop.
Save mr-v/13657584e3f9ed9e65f6 to your computer and use it in GitHub Desktop.
UIView<SomeProtocol> in Swift
import UIKit
protocol Droppable {
func dropped()
}
class A: UIView, Droppable {
func dropped() {
print("A")
}
}
class B: UIView, Droppable {
func dropped() {
print("B")
}
}
let a = A()
let b = B()
let aDropped: Droppable = a
aDropped.dropped()
let aView: UIView = a
aView.frame
/// T reflects: “I need a thing that conforms to the Droppable protocol and which is some kind of UIView.”
class Test<T: UIView where T: Droppable> {
let property: T
init(property: T) {
self.property = property
}
func printGenericConstraint<P: UIView where P: Droppable>(parameter: P) {
print(parameter)
}
func printProtocol(parameter: Droppable) {
print(parameter)
}
func printDroppables(droppables: [Droppable]) {
print(droppables)
}
func printViews(views: [UIView]) {
print(views)
}
}
let test: Test = Test(property: a)
test.property.frame
test.property.dropped()
test.printGenericConstraint(b)
test.printProtocol(b)
test.printGenericConstraint(a)
test.printProtocol(a)
test.printDroppables([a, b])
test.printViews([a, b])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment