Skip to content

Instantly share code, notes, and snippets.

@jorgenisaksson
Last active March 24, 2017 13:26
Show Gist options
  • Save jorgenisaksson/1f09bb1d3cd5363c6d596a6e28513731 to your computer and use it in GitHub Desktop.
Save jorgenisaksson/1f09bb1d3cd5363c6d596a6e28513731 to your computer and use it in GitHub Desktop.
Check if a class conforms to a protocol instead of using respondsToSelector like in obj-c
import UIKit
// the protocol
protocol LayerManagerDelegate: class {
func doSomething()
}
// the class
class LayerManager {
var layers = [CALayer]()
init() {
layers = [FirstLayer(), SecondLayer()]
}
func doSomeWork() {
// iterate over our layers and do something with layers conforming to the LayerManagerDelegate protocol
for someLayer in layers {
if let layerManagerDelegate = someLayer as? LayerManagerDelegate {
//layerManagerDelegate responds to the LayerManagerDelegate protocol =]
layerManagerDelegate.doSomething()
}
}
}
}
class FirstLayer: CALayer, LayerManagerDelegate {
func doSomething() {
print("I conform to the LayerManagerDelegate protocol")
}
}
class SecondLayer: CALayer {
func doSomethingElse() {
print("I don't conform to the LayerManagerDelegate protocol")
}
}
let layerManager = LayerManager()
layerManager.doSomeWork()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment