0

I am newbie on Swift.

I am trying to learn basics and structure. I have started a project, i am learning as i advance.

fatal error: unexpectedly found nil while unwrapping an Optional value

I am taking the exception above a few times while coding.

Although I have read the Apple documentation, my mind is not clear.

Could anyone tell the story about this exception and its causes, how is related with Optional on Swift?

Thanks

Code is as below

var globalDaily:Float = 0.0

for var i=0; i<favoritesArray.count; ++i {

    var tempDict:NSMutableDictionary = favoritesArray.objectAtIndex(i) as NSMutableDictionary
    let tempFloat:Float! = tempDict.objectForKey("amount") as? Float

    globalDaily = globalDaily + tempFloat//This line gives the bad access

}
1
  • Just a note. You don't need to force Float the number type is inferred from the fact you use 0.0. Commented Aug 21, 2014 at 8:52

2 Answers 2

1

In swift a variable must always contain a valid value. For value types (int, float, strings, structs, etc.) it means the variable must be initialized. For reference types (instance of classes) they must be initialized to a valid instance of a class and cannot be nil.

In swift a variable cannot be left uninitialized. But there are cases when it is allowed for a variable to be non initialized or initialized with nil. This is why the concept of optionals has been introduced. An optional variable can contain a valid value for its data type, or nil. An optional variable is declared by postfixing the question mark to the type, for instance: var x = Int?.

Suggested reading: Optionals in the Swift Programming Language book.

As for your problem, here:

let tempFloat:Float! = tempDict.objectForKey("amount") as? Float

you read a value from a dictionary, which can be nil if no value has been set for the amount key. That's why there is a cast as? Float. That casts to an optional type, which can either contain a valid Float type, or nil.

In the left side of the assignment let tempFloat:Float! you are stating that the right side is not nil (by using the exclamation mark), and that you can use tempFloat without unwrapping it.

If the dictionary contains a valid float for the amount key, then that's not a problem. But if the dictionary doesn't contain a value, what happens is that a nil is attempted to be converted to a Float when you try to use the tempFloat variable - which causes the exception.

The workaround looks like this:

let tempFloat = tempDict.objectForKey("amount") as? Float

if let unwrappedFloat = tempFloat {
    globalDaily = globalDaily + unwrappedFloat
}

this makes sure that you use the variable (and do the addition) only if tempFloat contains a valid float value.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you can use downcasting to Float only if Dictionary has AnyObject type

See example:

var globalDaily:Float = 0.0

var favoritesArray:Array<Dictionary<String,AnyObject>> = []

var item:Dictionary<String,AnyObject> = ["amount": 2.0]
favoritesArray.append(item)

for var i=0; i<favoritesArray.count; ++i{

    var tempDict:Dictionary = favoritesArray[i]

    if let tempFloat:Float = tempDict["amount"] as AnyObject! as  Float!{
        globalDaily = globalDaily + tempFloat // output 2
    }
    else{
        globalDaily = globalDaily + 5
    }

But if the key doesn't exist, we get 5

So if you know that you have Float type only, you can write just:

var globalDaily:Float = 0.0

var favoritesArray:Array<Dictionary<String,Float>> = []

var item:Dictionary<String,Float> = ["amount": 2.0]
favoritesArray.append(item)

for var i=0; i<favoritesArray.count; ++i{

    var tempDict:Dictionary = favoritesArray[i]

    if let tempFloat:Float = tempDict["amount"]{
        globalDaily = globalDaily + tempFloat
    }
    else{
        globalDaily = globalDaily + 5
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.