FF 937 POP Cheatsheet

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

POP Cheatsheet hackingwithswift.

com

You can extend any class or struct to add struct JediKnight { } Swift behaves differently depending on whether
custom methods, like this: you declare methods in your protocol. To show
extension JediKnight: ForceUser { } this, here’s a protocol method commented out:
extension UIView {
func disappear() { In that example, the JediKnight struct inherits protocol Targetable {
UIView.animate(withDuration: 3) the method implementation from ForceUser. // func takeDamage()
{ [unowned self] in }
self.transform = You can also provide new implementations
CGAffineTransform(scaleX: 0.001, y: inside your struct, overriding the default And here’s a default implementation:
0.001) implementation:
} extension Targetable {
} extension JediKnight: ForceUser { func takeDamage() {
} func turnToDarkSide() -> Bool { print(“I’m hit!”)
return true }
You can also define your own protocols that } }
include method stubs: }
This struct has its own implementation:
protocol ForceUser { You can constrain your code to add functionality
func turnToDarkSide() -> Bool to an object that conforms to a protocol if and struct XWing: Targetable {
only if it conforms to another protocol: func takeDamage() {
}
print(“I need the Force!”)
That’s all basic Swift functionality. What POP protocol HasNaughtyTendencies { } }
lets you do is attach default functionality to your }
protocol methods, like this: struct SithLord: ForceUser,
HasNaughtyTendencies { } Despite the custom implementation, this will
extension ForceUser { print “I’m hit” three times:
func turnToDarkSide() -> Bool { extension ForceUser where Self:
return false HasNaughtyTendencies { let fighters: [Targetable] =
} func zapPeople() { [XWing(), XWing(), XWing()]
} print(“Zap!”)
} fighters.forEach { $0.takeDamage() }
If you have default implementations for your }
protocol, then you can make any class, struct, or If you uncomment the method in the protocol
enum conform to it easily. that will change to “I need the Force!”

Thanks for being part of the Swift Frequent Flyer Club! Copyright © 2016 Paul Hudson

You might also like