Just about a month ago I started learning swift (mainly from books), with no prior programming experience whatsoever. I am still having trouble wrapping my head around several concepts, mainly value types and reference types, and things such as delegation. This is probably the reason why I can’t seem to find an answer for the following problem.
I have an Xcode project with 2 classes as in 2 swift files.
- A viewController class containing a collection view;
- A collectionViewCell class.
In the viewController class I have a method to disable and enable user interaction of the collectionView:
func collectionViewInteractionEnabled(boolean: Bool) {
collectionView.userInteractionEnabled = boolean
}
When called from the viewController class, the method works. But when called from the collectionViewCell class, i get this:
"fatal error: unexpectedly found nil while unwrapping an Optional value”
Xcode highlights the contents of my function as the culprit. This makes me think that the collectionView is not there for the collectionViewCell class. But my infant programming brain really can’t follow the thought process needed to figure this out.
The only solution I found was using a notification to let the function perform. It works, but isn’t there another way that I should know about? Is it possible to call a function from a different class, and still have it perform as if it was being called from the class wherein the function is declared?
Edit: Update after trying Patricks' advice:
The question mark does stop the app from crashing, but does not change the behavior of the code. The collectionView
is indeed created in storyboard with 3 outlets connected, the reference, and the datasource and delegate.
The function is called and performs correctly from within the viewController
class. So I assume that it is not nil. If i try to call it from the collectionViewCell
class (a different .swift file), then it aparently is nil. I thought the collectionViewCell' class just can't see it since the
collectionView` is created somewhere else? It makes no sense to me and the more I think about it, the more I get lost.
Could it be that I am just calling the function wrong from the other file? I am using:
In the collectionViewCell class
ViewController().collectionViewInteractionEnabled(true)