Skip to content

Instantly share code, notes, and snippets.

@sanketfirodiya
Created April 14, 2017 18:27
Show Gist options
  • Save sanketfirodiya/22623d668ebc941eb673ff5c61b8cb92 to your computer and use it in GitHub Desktop.
Save sanketfirodiya/22623d668ebc941eb673ff5c61b8cb92 to your computer and use it in GitHub Desktop.
Dangers of implicitly unwrapped optionals
//: 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
@plivesey
Copy link

Yep, this shows the problem.

@plivesey
Copy link

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