Stanford calculator app crashes with error "unexpectedly found nil" - ios

I'm new to programming and I've started taking the stanford course on iTunes U for making an iPhone 8 app. They're using Xcode 6 and Swift 1 while I'm in El Capitan using Xcode 7 and Swift 2. I've found a few differences in code that Xcode has been able to pick up on and help me correct ("println" is now "print" for example), but I'm getting tripped up on one particular part of the code:
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
I've double checked several times to make sure this is exactly how the teacher wrote it. His built correctly and functioned correctly, while mine builds correctly, but shows this fatal error when I try to operate it, "unexpectedly found nil while unwrapping an Optional value" (see screenshot for all the details).
Screenshot of the error
I've been looking around the internet and found a few similar examples, including one on this site (Stanford Calculator app keeps crashing), but after trying everything that was suggested I concluded that something must be unique in my system or I'm operating in a new Xcode/Swift environment than the others that had this problem. None of the solutions have resolved the problem, and all of them added errors of their own.
In responding to someone else's question someone suggested that we use this code to ensure that if "nil" is returned by "display" that it will provide "0" instead:
return (NSNumberFormatter().numberFromString(display.text) as? Double) ?? 0
I tried this, but it only gave me more errors, some seem to be related to Swift 2 (it required a comma after double, wanted me to unwrap display.text, and complained that there was an expected expression missing—maybe the suggested code was good in Swift 1??).

I've double checked several times to make sure this is exactly how the teacher wrote it. His built correctly and functioned correctly, while mine builds correctly, but shows this fatal error when I try to operate it, "unexpectedly found nil while unwrapping an Optional value"
I suspect that display is an IBOutlet property that needs to be connected to something in the user interface, probably a text field. If it's not connected, then even though your code is exactly the same, you'll get nil when you try to use its text property, and unwrapping that will cause the error you're seeing.
Whether or not the advice above actually solves your problem, what you really need to do is to set a breakpoint a line or two before the spot where the crash occurs and step through the code. Look at the variables involved and figure out where that nil value is coming from. You can work backward from there and figure out why the thing that you expect not to be nil is, in fact, nil. Learning to work that way will help you work out these kinds of problems when they occur (and they will occur again).

Not sure if you've found the answer or not by now, but I ran into a similar problem this morning and thought I'd share what I found.
While debugging, I entered two console logs to a simplified version of my operate like so:
case "x": if operandStack.count >= 2 {
print(" display before popping is: \(display.text!) ")
displayValue = operandStack.removeLast() * operandStack.removeLast()
print(" display after popping is: \(display.text!) ")
enter()
}
Display after popping came up as "newValue". I couldn't figure out what that meant at first, but realized that my issue is the setter. newValue is an optional that should be unwrapped i.e. "(newValue)!"
P.S. I opted to return:
return (display.text! as NSString).doubleValue
in my get.
Also, since newValue is unwrapped, keep in mind it will crash if display is set to nil.

Related

ibeacon app development using swift

everyone, I am a new one to iOS app development using swift.
I am studying a ibeacon app sample code which downloaded from the https://github.com/SelimSalihovic/CityOS-iBeacon-Swift-Tutorial.
while I was running the code, there are errors in the code as shown the following page, could you help me how to solve it, please! Thanks in advance!
The first one is easily solveable by unwrapping the value (the exclamation mark)
NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!
Second and third error are due to the beacons array not declaring the content's type (AnyObject means it can't be any class, which is not guaranteed to have the properties the code is looking for) so just go to line 16 and make the following change
var beacons : [CLBeacon] = []
However this will still not compile because the LocationServices framework hasn't been imported in the project, to do so just add
import CoreLocation
There will be some more errors now, specifically at line 26 and 55 in BeaconTableViewController
Fix-It has the right suggestion for these, basically you need to cast note.object by adding as! [CLBeacon] and remove the unwrapping on switch proximity because the value isn't optional
The code now compiles properly for me, I'm not sure it will work because I can't test right now, but it should be a step in the right direction
Good luck with your journey in iBeacons, they're a pretty fun technology to work with

why xcode's suggested error fix (goes back and forth with no end) in these statements?

I have this line, written with Swift 1.2 using XCode 6
self.mainMenuButton.titleLabel?.font = UIFont(name: Box.fontName, size: mainMenuButton.titleLabel?.font.pointSize!)
it shows this error
operand of postfix "!" should have an optional type
it basically suggests that I change it to this
self.mainMenuButton.titleLabel?.font = UIFont(name: Box.fontName, size: mainMenuButton.titleLabel?.font.pointSize)
and when done it requires that i put the ! back like in the first line, so it loops in the suggestions without ending...
why does this happen and how to solve it?
Ahh, I have encountered this problem multiple times! Really confusing. The problems lies in the UIFont init statement:
UIFont(name: ..., size: mainMenuButton.titleLabel?.font.pointSize!)
The problem is that the UIFont initializer requires a non-optional size argument. But in your code, mainMenuButton.titleLabel?, the ? says that mainMenuButton.titleLabel?.font.pointSize! can return an optional, regardless of whether you put a ! at the end.
Solution
The solution is to change the ? behind titleLabel to a !.
Explanation for error fix going back and forth
Xcode is not smart enough to know that the ? is the root cause of the problem, it just thinks that since the expression ultimately returns pointSize, you should add a ! to ensure that pointSize is not nil. But, as shown in the documentation, pointSize is not an optional! So there's no need to unwrap it using !. That's why Xcode suggests to remove the !. But removing it causes the expression to be return an optional! And the size argument only allows non-optionals! So the Fix-It cycles back and forth...
Edit
Also, I tested it and this error going back and forth problem is fixed in Xcode 7. Compared to Xcode 7, Xcode 6 is already obsolete.
As blip explained, watch out for "?"
These typically pop up when you need to use a "!" or "?" and Xcode typically falls back to "?".
If you are trying to display something on the user's screw and it shows as optional("blah blah"), look for any "?" leading up to the code that prints the line and force unwrap it "!"

Swift 2.0 Subscript issues with Dictionary

I've looked at the other questions on here about subscripting with dictionaries and I didn't see anything that quite fit what my scenario is. It may be that I'm still too new to Swift to realize it but in any case here is my scenario. I'm getting the typical can't "Subscript" dictionary with type string. I've seen the posts on here about it being an optional and needing to unwrap it however when I try that, Xcode suggests that I remove the !, so I do that, then I get the subscript error.
I've watched tons of tutorials on swift development and a lot of them use playgrounds and I never remembered seeing anyone have to do this in any of the tutorials. So I tried the same thing in a playground and it worked.
Here is what I have in the ViewController that DOESN'T work.
var validFields:Dictionary = ["loanBalanceInput":false,"cashOutInput":false,"appraisedValueInput":false,"interestRateInput":false]
func validationSuccess(sender:UITextField){
sender.backgroundColor = green
switch sender {
case loanBalanceInput:
validFields["loanBalanceInput"] = true
break
default:
break
}
}
What I've done is create a dictionary of strings that refer to textfields and their validation status to track whether or not they have been validated. The concept is that when everything in the dictionary is true, I can activate the calculate button.
However I get the "cannot subscript a value of type dictionary with an index of type string" error... However this code in a playground works...
var validatedFields:Dictionary = ["loanBalanceInput":false,"cashOutInput":false,"appraisedValueInput":false,"interestRateInput":false]
validatedFields["loanBalanceInput"]
validatedFields["loanBalanceInput"] = true
I don't understand what's going on here. Is it because this is an optional?
#IBOutlet weak var loanBalanceInput: UITextField!
I'm not unwrapping it in my switch? I'm not trying to get at the value of loanBalanceInput though, I'm just checking to see if it was the sender.
Normally a Swift Dictionary declaration needs also the type of the containing keys and values like
var validFields: Dictionary<String,Bool> = [" ...
but as the compiler can infer the type just delete the annotation.

How to debug 'fatal error: unexpectedly found nil while unwrapping an Optional value'

There are a lot of questions on Stack Overflow related to this error. I’ve read some excellent posts on how Optionals work and this error in particular. However, I haven’t found any information about the best way to figure out which value is being set to nil and causing the error in the first place.
Are there any good debugging techniques to find out which Optional is causing this error?
Here's at least half an answer (would the other respondents please read the question first!): Use the simulator instead of an actual iOS device.
The debugger seems to be pretty good at pointing to the line with the maltreated optional that's causing the trouble... unless you are like me, choosing to run the code on an iOS device directly from time to time. In the latter case, the debugger lands me right in the middle of some assembler code with no sensible stack trace. Switching back to the simulator gives the exact line of code at fault.
You Xcode does not crash at the incorrect line of code?
This does not response to the question but it's important to note:
When you are not sure about an optional variable, you have to verify if it contains value or not, by using a pattern like this:
var myOptional : String?
if let aString = myOptional {
//do your work with aString.
}
What basically optional value is "?" when you place ? after a datatype that is optional while if it is unwrapped and a nil appears theres no error but it you place "!" exclamation mark after datatype then if it unwrap the variable and nil appears then there's crash or error so often use optional as
var myVariable : DataType ? = DataType()
or
var myVariable : DataType ? = nil
or
var myVariable : DataType ? = value
An optional in Swift is a variable that can hold either a value or no value. Optionals are written by appending a ? to the type:
var myOptionalString:String? = "Hello"
Some places optionals are useful:
When a property can be there or not there, like middleName or spouse
in a Person class
When a method can return a value or nothing, like
searching for a match in an array
When a method can return either a result or get an error and
return nothing
Delegate properties (which don't always have to be set)
For weak properties in classes. The thing they point to can
be set to nil
For a large resource that might have to be released to
reclaim memory
https://medium.com/#rrridges/swift-optionals-a10dcfd8aab5

Swift Optionals - Inconsistency?

I'm slightly confused - I thought I understood Optionals and on the Apple dev forums Chris L, mentioned a work around to the immutable Optional issue was to create a class wrapper for the optional value type. -link!
However take this example with UIWindow (an optional class type with various properties)
The properties still don't seem mutable with optional chaining!
var window: UIWindow?
//this works (force unwrap)
self.window!.backgroundColor = UIColor.greenColor()
//this optional chain doesn't work... why not? Isn't this just a safer version of the above?
self.window?.backgroundColor = UIColor.redColor()
This seems to be fixed in beta 5!
update for Xcode beta 5
the originally asked issue has been resolved in Xcode beta5, that may invalidate this answer.
original anwer
that may request further explanation, why it is definitely not inconsistent behaviour but is simple invalid.
the optional value has to be always of the right side of the actual operand, and it cannot be on the left side of it.
see that logic via two simple examples:
example 1
in case of this line of code:
self.window?.backgroundColor = UIColor.redColor()
< LEFT ^ RIGHT >
the optional is on the left side which would mean the left side could be nil therefore the following operand would appear here in runtime:
nil = UIColor.redColor()
which is clearly invalid on every level without any further or complex explanation – a nil cannot be assigned to something else, that is why the compiler does not allow it.
NOTE: you may assume that the logical behaviour would be like this in the case of self.window = nil:
nil.backgroundColor = UIColor.redColor()
but the documentation about Optional Chaining highlights a very important behaviour which explains why that is not happening at all:
Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
emphasis is on the word "entire", thus that is why the left side will be nil = ... and not nil.backgroundColor = ... as you'd expect after Objective-C.
example 2
the other answer highligths another idea of how it can be solved:
self.window?.setBackgroundColor(UIColor.redColor())
why is that working? would it not be a little inconsistency here? definitely not.
the actual optional is on the right side of the operand here, because that line is equal to this line, however we are not bothered to get the void in practice at all.
let result: Void! = self.window?.setBackgroundColor(UIColor.redColor())
< LEFT ^ RIGHT >
as you see there is not any inconsistency at all here, because in the case of self.window = nil that line would be equal to this one in runtime (please see the explanation above):
let result: Void! = nil
and that would be a completely legal operand.
the logic is simple, the optional must be always at the right side of the operand (or operator), on the left side it can be non-optional value only.
Optional chaining works for reading values (return value or nil), it works for calling methods (call this method or do nothing) but doesn't work for assignments.
I believe this is by design but I don't see a reason why it is so because this is essentially the same as:
extension UIWindow {
func setBackgroundColor(color: UIColor) {
self.backgroundColor = color
}
}
self.window?.setBackgroundColor(UIColor.redColor())
and that works without problems. You can report a bug or ask on the dev forums.
I believe optional chaining here is logically inconsistent.
Your example from dev forums doesn't have anything to do with this problem since that problem is about value types.

Resources