Created
April 14, 2017 18:27
-
-
Save sanketfirodiya/22623d668ebc941eb673ff5c61b8cb92 to your computer and use it in GitHub Desktop.
Dangers of implicitly unwrapped optionals
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
//: Playground - noun: a place where people can play | |
import UIKit | |
import PlaygroundSupport | |
class ViewController: UIViewController { | |
lazy var tapHandler: TapHandler = TapHandler(delegate: self, view: self.view) | |
} | |
extension ViewController: TapHandlerDelegate { | |
func handleTap() { | |
} | |
} | |
protocol TapHandlerDelegate: class { | |
func handleTap() | |
} | |
class TapHandler { | |
weak var delegate: TapHandlerDelegate! | |
init() { | |
} | |
init(delegate: TapHandlerDelegate, view: UIView) { | |
self.delegate = delegate | |
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapReceived)) | |
view.addGestureRecognizer(tapGestureRecognizer) | |
} | |
@objc func tapReceived() { | |
self.delegate.handleTap() | |
} | |
} | |
var tapHandler = TapHandler() | |
autoreleasepool { | |
let viewController = ViewController() | |
tapHandler = viewController.tapHandler | |
print(tapHandler.delegate) //prints the viewController | |
} | |
print(tapHandler) | |
print(tapHandler.delegate) // crashes |
You could also change the last line to tapHandler.handleTap()
which would make it more 'real world'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yep, this shows the problem.