martin
martin

Reputation: 1974

NSDictionary returning an optional integer when retrieving information

I have dictionary declared like this:

var friendLetterCount:NSDictionary = NSDictionary(dictionary: [String:Int]())

and I obviously want to retrieve the information for the keys in the Dictionary, but when I do it, it only returns optional integers, how do I make this so that they are integers only?

I retrieve like this:

friendLetterCount["a"]

and when I print it to the console it says

optional(1)

I've tried converting it in all the ways I can imagine, but it always gives me an error saying

'(NSObject, AnyObject)' is not convertible to 'Int'

Any suggestions would be appreciated.

Upvotes: 0

Views: 3857

Answers (3)

Abhijith
Abhijith

Reputation: 3394

In case if you are not sure about the value is always Integer (Usually happens this with String/Intger),the safest way is :

if let count = friendLetterCount["a"]?.integerValue  {

}

Upvotes: 0

Alvin George
Alvin George

Reputation: 14296

class AppModel: NSObject {

private  var _user_id:String?

final func serviceResult(results:NSObject) {

var data = results as? NSDictionary
_user_id = String (data?.objectForKey("userId") as! Int)
 println("user id \(_user_id)")

}

}

Note: AppMOdel is a NSObject class, results is the parsed JSON DATA, data- NSDictionary, _user_id is a private variable.

It return the print as : 

user id Optional("8")

Upvotes: 0

rakeshbs
rakeshbs

Reputation: 24572

The Optional(1) value just means that the value is an optional swift type.

You can unwrap the value from an optional using the ! operator.

let a = friendLetterCount["a"]! as Int
println(a)

a will the unwrapped value.

You can also use optional binding to check for nil while also doing unwrapping.

if let a = friendLetterCount["a"] as? Int
{
    println(a)
}

Please learn about Optionals from Apple's Swift Book.

Also you can read articles like this http://www.appcoda.com/beginners-guide-optionals-swift/

Upvotes: 4

Related Questions