I am experimenting with Protocols and Delegates and I am stuck while initializing the delegate.
At the top my of my class, I tried adding
protocol myDelegateProtocol {
func clickedCellIndexPath(indexPath: Int)
}
class MyClass {
var myDelegate : myDelegateProtocol
override init() {
super.init()
self.setup() // error 1
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder) // error 2
}
}
It started giving errors for both init closures
Both errors:
Property 'self.myDelegate' not initialized at super.init
What am I missing or doing wrong?
If I try declaring it as var myDelegate: myDelegateProtocol?
, it doesn't give that error, but it forces me to force unwrap myDelegate!
and it returns nil at this point.
Edit: If I force it unwrap at the top, then I receive error in the following parts..
...
var myDelegate : myDelegateProtocol!
func handleTap(sender: UITapGestureRecognizer? = nil) {
if let point = sender?.locationInView(collectionView) {
print("Y")
let clickedCell = collectionView!.indexPathForItemAtPoint(point)!.row
print(clickedCell) // prints
self.myDelegate.clickedCellIndexPath(clickedCell) // error here
}
}
Edit 2:
So my complete code..:
protocol myDelegateProtocol {
func clickedCellIndexPath(indexPath: Int)
}
class MyClass {
var myDelegate: KDRearrangableClickedCellDelegate!
override init() {
super.init()
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup() {
if let collectionView = self.collectionView {
let tap = UITapGestureRecognizer(target: self, action: #selector(KDRearrangeableCollectionViewFlowLayout.handleTap(_:)))
tap.delegate = self
collectionView.addGestureRecognizer(tap)
}
}
func handleTap(sender: UITapGestureRecognizer? = nil) {
if let point = sender?.locationInView(collectionView) {
let clickedCell = collectionView!.indexPathForItemAtPoint(point)!.row
print(clickedCell)
self.myDelegate.clickedCellIndexPath(clickedCell)
}
}
And I receive this error at this point:
fatal error: unexpectedly found nil while unwrapping an Optional value