Last active
March 24, 2017 13:26
-
-
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
This file contains hidden or 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 | |
// 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