I used this code to get access to the root view controller from within my app delegate. Here's the question - why do I need to have an exclamation point at the end of the first line, and also at the beginning of the second line (after rootController)? It seems like I have forced an unwrap of the optional UIViewController that is a property of the UIWindow on two separate lines. This code works just fine the way it is here. It also works if I remove the exclamation at the end of the first line and put two exclamation points after rootController on the second line/
let rootController = application.windows[0].rootViewController!
rootController!.view.backgroundColor = UIColor.lightGrayColor()
It's because the windows property of UIApplication is an array of AnyObject. I know it seems a bit weird at first, but basically you can think of the first ! as force downcasting the AnyObject to a UIViewController? and then force unwrapping the optional UIViewController? to finally get the UIViewController.
You can check to see how it won't tell you to put two exclamation points if you force downcast the windows[0] first and then do the rest:
let rootController = (application.windows[0] as! UIWindow).rootViewController
rootController!.view.backgroundColor = UIColor.lightGrayColor()
Your first exclamation point acted as that as! when you didn't explicitly cast.
Hope this helps.
Related
I've read several answers to this question and have tried all recommendations with no success. I'm fairly new to swift and am building an app with Swift, PHP and MySQL. I'm receiving the error after the user has logged in to the app and the system should be displaying the username via a label using UILabel.text. The error is occurring on setting a value to the UILabel.text variable. My code is included below. I've tried to hardcode values on other pages and am getting this error throughout my project.
import UIKit
class HomeViewController: UITabBarController {
#IBOutlet var usernameLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// set global variables
let username = (user!["username"] as AnyObject).uppercased
// label values
print(usernameLbl ?? username!)
usernameLbl.text = username
}
}
I'm accessing the HomeViewController programmatically. The app uses a tab bar and the first page of it is Home. The code is from a course I'm taking on Udemy. Here is how I'm accessing Home:
// func to pass to home page or to tabBar
func login() {
// refer to our Main.storyboard
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// store our tabBar Object from Main.storyboard in tabBar var
let tabBar = storyboard.instantiateViewController(withIdentifier: "tabBar")
// present tabBar that is storing in tabBar var
window?.rootViewController = tabBar
}
You might want to follow best practices and avoid the use of ! as much as possible.
The error you've got happens when you try to access a value or reference stored in an optional that does not contain any value (i.e., it is nil).
In your case, if usernameLbl is nil, usernameLbl.text will crash your app (Think "null pointer exception" in Java, perhaps?).
It is very common to define outlests as:
#IBOutlet weak var label: UILabel!
...instead of the safer:
#IBOutlet weak var label: UILabel?
...because the first one allows you to access its properties without using the ? (i.e. label.text vs. label?.text). But there's an implicit assumption that the label is not nil: the ! by itself does nothing to prevent this (it only silences the compiler, telling it "I know what I'm doing, trust me!").
That shouldn't be a problem as long as you only access it after viewDidLoad() and your outlets are proerly connected in Interface Builder/storyboard, because in that case it will be guaranteed to not be nil.
My guess is that you forgot to hook up the outlet to your label.
Here is a tutorial on storyboards in case it helps.
The whole reason outlets need to be defined as optionals (implicitly unwrapped ! or "standard" ?) is that in Swift, all properties must have a value by the time the instance is initialized (actually, even before calling the super class initializer if that applies).
For view controllers, instance initialization happens before the subviews can be initialized and assigned to the properties/outlets. That happens in the method loadView(), which is called lazily (only just before the view is actually needed for display). So by making all subviews optional (and variable, not constant), they can have the temporary "value" of nil by the time the initializer completes execution (thus satisfying Swift's rules).
Edit: If your outlet is still nil at runtime even though it is connected in interface builder, you can at least try to intercept any code resetting it and see what's going on, with a property observer:
#IBOutlet weak var label: UILabel! {
didSet {
if label == nil {
print("Label set to nil!")
// ^ SET A BREAKPOINT IN THIS LINE
}
}
}
Seeing an #IBOutlet on a UITabBarController is very suspicious. You generally have a tab bar controller which presents child UIViewController subclasses, and put labels on those child view controllers, not the tab bar controller. A tab bar controller does not generally have IBOutlet references. The child view controllers would have them.
Double check to which class you've connected that #IBOutlet and confirm whether it's a subclass of UIViewController or UITabBarController.
Think of the ! operator as the "crash if nil" operator. It's actually called the "force unwrap" operator, and is used to "unwrap" an Optional. If the optional contains a nil, it triggers the same error as trying to dereference a null pointer in other languages.
You should avoid the ! operator until you really understand what it does.
IB (Interface Builder) sets up outlets as force-unwrapped so that you can reference them without having to constantly check them for nil. The idea is that your outlets should never be nil, and if they are it's a problem and you WANT to crash. Think of it as a fuse. It triggers an obvious, early failure that's easy to find and fix.
Having a broken outlet (or missing IBAction) is one of the easiest mistakes to make. With an outlet declared as
#IBOutlet var someOutlet: UILabel!
The compiler lets you reference it without unwrapping it, but you will crash if the outlet is nil.
You can avoid the force-unwrap by adding a ? after the outlet name, or using and if let or a guard statement.
However, with outlets, the thing to do is to realize you've got a broken outlet and just fix it. Then your code works fine.
To fix a broken outlet, control-drag from IB to the #IBoutlet declaration in your code. Think of it as hooking up a cable in your entertainment system.
When you declare an outlet in your code the editor puts a little open circle in the margin to the left of the #IBOutlet declaration. When the outlet is connected, the editor shows a filled-in circle, so it's easy to see if an outlet is connected or not. (Same with #IBAction methods.)
let someVC = self.storyboard!.instantiateViewControllerWithIdentifier("something") as! SomethingViewController
why do we need to use "as! DataEntryViewController"
it works when I take it out using xcode 7.3.1
Define "works".
Yes, you can instantiate a view controller without caring which subclass of UIViewController it is. And the object you get back from that method will be a view controller, so it's safe to do things with it that can be done to all view controllers: present it modally, push it onto a navigation controller, add it to a tab controller, etc.
However, if you're going to do something with it that's specific to your view controller class -- like if SomethingViewController defines a property that lets you choose which Something it displays, and you want to assign to that property -- you need to do two things:
Test at runtime that the object you got back from instantiateViewControllerWithIdentifier is the class you expect it to be. (Because depending on the identifier you pass it could be some other class, or nothing at all if that identifier isn't in the storyboard.)
Let the compiler know that the variable you've assigned that object to is typed for that class, so that the compiler will let you access properties and call methods of that class.
Assignment with an as? or as! cast does both of those things in one step. (Whether to use as? or as! just depends on how much you trust yourself to make sure your storyboard identifiers are what they claim to be, and how you want to handle failure of such assumptions.)
In fact, even if you're not using properties or methods specific to that view controller class, that as! cast adds a runtime check that your view controller class is what you expect it to be. So the fact that nothing breaks when you take the cast out isn't a sign that the cast is superfluous — it's a sign that whatever breakage the cast was checking for is not currently happening.
That is, the line you quoted would lead to a crash if somebody changed your storyboard so that the identifier "something" was on a SomethingElseViewController. If you took that cast out, you wouldn't crash there. (And you'd probably run into trouble later.)
However, if what you really want to do is assert the validity of your storyboard and program, it might be better to be clear about that:
let someVC = self.storyboard!.instantiateViewControllerWithIdentifier("something")
assert(someVC is SomethingViewController)
// then do something non-SomethingViewController-specific with it
Update: with 2 downvote of this question, I'd like to make this question a little bit useful to others - since I don't have the choice to delete it. The mistake I made was cut and paste codes which has interface outlet. As I was completely new at that time, I was assuming that when I copy and paste, the outlet link will be copied and pasted as well. Obviously it doesn't work that way.
I was writing a single-viewed app. It has one UITextField and one MKMapView. I want to do something when Return key is hit, so I basically followed
How to hide keyboard in swift on pressing return key?
But it does not fit well with my other codes. Any idea why it isn't working and how to fix it?
Make sure you connect your UITextField from StoryBoard to your searchText IBOutlet by control-dragging from the StoryBoard to the the searchText variable.
You have your outlet set up as implicitly unwrapped. That's the correct thing to do, but when your code executes the outlet must not be nil or your code will crash.
You probabably have a broken outlet link. Set a breakpoint and examine the outlet.
You can change your code to use an "if let" expression to prevent crashes. Search in the Swift language reference IBook for "Optional binding" to learn about it.
Edit:
The code might look like this:
if let requiredSerachText = searchtext
{
requiredSearchText.delegate = self
}
I have created a UINavigationController object and set it as the window's rootViewController property.
The rootViewController of the UINavigationController object is a class called UINavigationMenuViewController.
If I want to navigate from UINavigationMenuViewController to UIUserProfileViewController for example, I can use:
navigationController!.pushViewController(userProfileVC, animated: true)
as well as
navigationController?.pushViewController(userProfileVC, animated: true)
The effect seems to be the same. I am wondering what's the difference.
I would guess the second way is more secure, and in case I forget to embed the UINavigationMenuViewController object inside the UINavigationController, the app would not crash, comparing to the first case. I guess it's also called optionals chaining, I am just not quite sure as I am still learning Swift.
Please give me some advice.
In case of doubt, it's always safer favoring optional chaining rather than forced unwrapping, for the reason you mentioned: if the variable is nil, it will cause the app to crash.
There are some cases where a crash is a good debugging tool though. If having your navigation controller set to nil, you might want to consider that as a development mistake, so making the app crash would make the mistake more explicit.
Besides that, my recommendation is to always use optional chaining and/or optional binding, and limit usage of forced unwrapping to cases where:
you are sure an optional is not nil
you have just checked for not nil
(as mentioned above) you do want the app to crash if the optional is nil
In the first case you unwrap navigationController explicitly so navigationController IS a UINavigationMenuViewController type and has to exist (or else crash). In the second case navigationController is an optional type and doesn't have to exist. If it doesn't exist of course nothing will happen and no view will be presented.
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
return 5
}
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
// Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
cell.labelTitle.text = "This is a title"
return cell
}
Does anyone know about this?
You can prevent the crash from happening by safely unwrapping cell.labelTitle with an if let statement.
if let label = cell.labelTitle{
label.text = "This is a title"
}
You will still have to do some debugging to see why you are getting a nil value there though.
Almost certainly, your reuse identifier "title" is incorrect.
We can see from the UITableView.h method signature of dequeueReusableCellWithIdentifier that the return type is an Implicitly Unwrapped Optional:
func dequeueReusableCellWithIdentifier(identifier: String!) -> AnyObject! // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
That's determined by the exclamation mark after AnyObject:
AnyObject!
So, first thing to consider is, what is an "Implicitly Unwrapped Optional"?
The Swift Programming Language tells us:
Sometimes it is clear from a program’s structure that an optional will
always have a value, after that value is first set. In these cases, it
is useful to remove the need to check and unwrap the optional’s value
every time it is accessed, because it can be safely assumed to have a
value all of the time.
These kinds of optionals are defined as implicitly unwrapped
optionals. You write an implicitly unwrapped optional by placing an
exclamation mark (String!) rather than a question mark (String?) after
the type that you want to make optional.
So, basically, something that might have been nil at one point, but which from some point on is never nil again. We therefore save ourselves some bother by taking it in as the unwrapped value.
It makes sense in this case for dequeueReusableCellWithIdentifier to return such a value. The supplied identifier must have already been used to register the cell for reuse. Supply an incorrect identifier, the dequeue can't find it, and the runtime returns a nil that should never happen. It's a fatal error, the app crashes, and the Console output gives:
fatal error: unexpectedly found nil while unwrapping an Optional value
Bottom line: check your cell reuse identifier specified in the .storyboard, Xib, or in code, and ensure that it is correct when dequeuing.
Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String). If so, then remove that line of code.
See this answer for more info:
Why is UICollectionViewCell's outlet nil?
"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."
I don't know is it bug or something but your labels and other UIs does not initialized automatically when you use custom cell. You should try this in your UICollectionViewController class. It worked for me.
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "<WhateverYourNibName>", bundle: nil)
self.collectionView.registerNib(nib, forCellReuseIdentifier: "title")
}
Replace this line
cell.labelTitle.text = "This is a title"
with
cell.labelTitle?.text = "This is a title"
I got his error when i was trying to access UILabel. I forgot to connect the UILabel to IBOutlet in Storyboard and that was causing the app to crash with this error!!
I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.
I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.
In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.
fatal error: unexpectedly found nil while unwrapping an Optional value
Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.
:) hopes it will help for some struggled people .
I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.
First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )
I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.
var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).
So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.
Im guesssing your label should always be there?
So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.
Nil Coalescing Operator can be used as well.
rowName = rowName != nil ?rowName!.stringFromCamelCase():""
I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.
I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-" calls and make sure the name is correct.
Same message here, but with a different cause. I had a UIBarButton that pushed a segue. The segue lacked an identifier.