Intricate access to dictionary key - ios

From a server I receive a JSON string, then I try to convert it to an NSDictionary this way:
let JSON = try NSJSONSerialization.JSONObjectWithData(rToData!, options:[])
guard let JSONDictionary:NSDictionary = (JSON as! NSDictionary) else {
print("My grandma is way more NSDictionary than this")
return
}
Once converted, I try to get some data contained in the dictionary: in particular I need an array I can access this way:
let myArray = JSONDictionary["data1"][0]["data2"];
XCode really doesn't like this idea, it puts an arrow under the first bracket and says Value of optional type "AnyObject?" not unwrapped, did you mean to use "!" or "?" ?. I follow its suggestion and I insert a "!", converting my preceding code to this:
let myArray = JSONDictionary["data1"]![0]["data2"];
At this point, the following line (where I count the number of elements in data2) shows an error, stating AnyObject has no member count.
The only thing that seems to work fine is this solution but, apart from being ugly and unreadable, I really don't understand it:
let myArray = (JSONDictionary["data1"]?[0]["data2"])!;
Can you help me understand why this basic access to a key in a dictionary must be so intricate?
I must say I like Swift but I spend a lot of time dealing with optionals and bizarre XCode alerts.

There is no guarantee that your JSON dictionary will contain a value for the key data1 (OK, you know it will, but Swift doesn't) so JSONDictionary["data1"] returns an optional. You need to unwrap the optional with ? or !
Also, since you have an NSDictionary, not a Swift dictionary, Swift doesn't know the type of the values, so they are AnyObject. Now again, you know it is an array, but Swift doesn't so you get an error stating that AnyObject doesn't have a count method.
While it is more verbose, it is cleaer for both the compiler and anyone else looking at your code if you split the line into multiple lines. It also lets you downcast the various objects so that Swift knows what is going on and handle any malformed JSON;
if let array1 = JSONDictionary["data1"] as? NSArray {
if let dictionary1 = array1[0] as? NSDictionary {
if let data2Array = dictionary1["data2"] as? NSArray {
let count=data2Array.count
}
}
}
You could implement appropriate else statements to handle errors
Optionals are one of Swift's most powerful features. They help avoid a whole family of bugs associated with uninitialised variables and special sentinnel values for boundary conditions. It is important that you learn how they can help you and not just throw ? or ! at your code until it compiles.

Related

How can I convert a string in a textfield to an Int in Swift?

I tried for a long time to turn the text into an Int but it did not work. I tried it like this:
(AnzahlString is a textfield)
var AnzahlAInt = 0
if let AnzahlAString = AnzahlString.text {
let AnzahlAInt = Int(AnzahlAString)
}
But then I always get the error:
Value of optional type 'Int?' must be unwrapped to a value of type 'Int'
Then I added a ! at the end of Int(AnzahlAString)! so I don't get a error, but now when I press on the button, the app crashes. It was predictable, but how can I change this now to an Int without the !?
At first glance, it looks like you have two things to check for:
is AnzahlString.text present, and
does it represent an Int
The first check is in fact not necessary, since .text will never return nil, even though it's marked as Optional. This means you can safely force-unwrap it.
The second check is easily done by using the ?? operator:
let AnzahlAInt = Int(AnzahlString.text!) ?? 0
PS, just as a stylistic hint: variable names in Swift ususally start with a lowercase letter, names starting with capital letters are used for types.
PPS: your code as written shadows AnzahlAInt - the value of your var is never changed.
The reason why the resulting Int is optional, is that parsing might or might not succeed. For example, if you try to parse the string "Fluffy Bunnies" into an Int, there is no reasonable Int that can be returned, therefore the result of parsing that string will be nil.
Furthermore, if you force the parser by using !, you're telling Swift that you know for sure that the string you pass will always result in a valid Int, and when it doesn't, the app crashes.
You need to handle the situation in which the parse result is nil. For example:
if let AnzahlAIntResult = Int(AnzahlAString) {
// We only get here if the parse was successful and we have an Int.
// AnzahlAIntResult is now an Int, so it can be assigned to AnzahlAInt.
AnzahlAInt = AnzahlAIntResult
}
You did a good job so far but missed out one thing.
This line tries to convert the String into an Int. However this can fail, since your String can be something like this "dfhuse".
let AnzahlAInt = Int(AnzahlAString)
This is why the result of Int(AnzahlAString) is an Optional (Int?). To use it as an real Int, you have to unwrap it.
First solution is the !, however, every time this does fail your app crashes. Not a good Idea to use so.
The best solution would be Optional Binding, as you already used to get the text of your text field.
if let AnzahlAString = AnzahlString.text {
if let safeInt = Int(AnzahlAString) {
// You can use safeInt as a real Int
} else {
print("Converting your String to an Int failed badly!")
}
}
Hope this helps you. Feel free to ask again if something is unclear.
For unwrapping you can also use guard like this
Simple and easy
guard let AnzahlAInt = Int(AnzahlString.text!) else {
return
}
print(AnzahlAInt)

App crashed when getting string from Dictionary (swift)

I converted a JSON to Dictionary and got some String by
title = json?.objectForKey("Titel_Live") as! String
But some times app will be crashed. I cannot reproduce this problem, just get information from crash reports.
Could someone help me and tell why? Thanks
Error at line 163
Crash reports
title = json?.objectForKey(“Titel_live”) as! String
This line of code where you are doing force unwrapped (Don't force the cast using !) is the cause means if object with key Titel_live dot not find then should be crashed, better go with optional chaining or use gaurd but yes your Json does't contain any object with key Titel_live(may be spelling mistake or object is array so validate once).
//better go like this check if exist or not.
if let t = json?.objectForKey(“Titel_live”) {
title = t
}
You should not force the casting to String.
You can try :-
title = json?.objectForKey("Title_Live") as? String (if title is optional variable)
if title is not optional then use:
title = (json?.objectForKey("Title_Live") as? String ?? "")
Because objectForKey will return nil if no value is associated with that key and force casting nil to String fails and causes crash.

Swift 2.2 breaks optionals/unwrapping optionals

Swift 2.2 has broken almost all my code. Even this simple string assigning to label doesn't work anymore:
cell.categoryName.text = peopleArray![indexPath.row]["Name"] as? String
The error says "Downcast from 'String?!' to 'String' only unwraps optionals, did you mean to use '!!'?"
What changes do I have to do now.
EDIT:
More Problems:
if (dict["data"]!["DataDetails"] as! NSArray).count == 0 {
}
Due to this I am getting a segmentation fault and the error shows this: warning: cast from 'String?!' to unrelated type 'NSArray' always fails
UPDATE:
I was using NSDictionaries, NSArrays in my classes that seems to cause the problem. Changing all the literals from Obj-C to swift made the code work properly.
So, I will also recommend other developers to prefer swift literals.
it seems there are some slight differences when using the swift types and the objective-c NS... types
eg
let dic:NSDictionary? = ["a":"a"]
let str:NSString? = dic!["a"] as? NSString
let dic2:Dictionary? = ["b":"b"]
let str2:String? = dic2!["b"] //dont need to do any casting, already optional
print(str)
print(str2)
prints
Optional(a)
Optional("b")
so depending on how your array / dictionary is defined, you might need different casting/unwrapping

Cast from 'MDLMaterialProperty?!'?

I'm working with the parse framework for an App that I'm converting to Xcode 7. One of the interesting errors which has occurred as part of migrating the project is the following:
Cast from 'MDLMaterialProperty?!' to unrelated type 'PFUser' always fails
The offending line seems to be the "if let" clause below. I've commented the old line which worked fine in the previous version of Swift for comparison.
With respect to what this is actually doing - I've passed an array of Parse objects into "likesForThankful" where a pointer "userID" refers to a related PFUser. As part of this method I'm writing individual PFUsers to an array.
Any help is appreciated - thanks in advance.
//Add PFUsers who Like Post to our FeedItem
private func callbackFromLikesProcessing(likesForThankful:[AnyObject], againstFeedItem:FeedItem){
//Instantiate our Objective C compatible array for processing later
againstFeedItem.parseUsersObjectsWhoLikePost = NSMutableArray()
//Loop through likes and add PFUsers to array of users who like post
for usersWhoLikePost in likesForThankful{
// if let parseUserWhoLikesPost = usersWhoLikePost["userID"] as PFUser{
if let parseUserWhoLikesPost = usersWhoLikePost["userID"] as? PFUser {
againstFeedItem.parseUsersObjectsWhoLikePost.addObject(parseUserWhoLikesPost)
}
}
Andrew
Figured this out if it can help anyone - it's basic Swift Syntax (though I'm not sure why the compiler let me get away with this in the first version of Swift!).
Because usersWhoLikePost is a PFObject which happens to contain a pointer to a PFUser object I needed to conditionally unwrap this first like so:
for usersWhoLikePost in likesForThankful{
if let parseLikeObject = usersWhoLikePost as? PFObject{
if let parseUserWhoLikesPost = parseLikeObject["userID"] as? PFUser {
againstFeedItem.parseUsersObjectsWhoLikePost.addObject(parseUserWhoLikesPost)
}
}
}
After this I could continue as I had previously done and access the "userID" property with a conditional unwrap of the PFUser object.

Swift Int is not convertible to DictionaryIndex?

I'm trying to convert this piece of ojb-c code:
MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
to swift, and as such I have this:
var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey.integerValue];
However this gives me the error in the title.
What am I doing wrong here?
You have a few problems, first of all in your direct translation:
var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey.integerValue];
The ] is in the wrong place, so you're trying to call integerValue on MPMoviePlayer... instead of on the dictionary lookup.
var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey].integerValue;
This is still failing because userInfo is an NSDictionary and not a Dictionary, so it gets mapped to [AnyObject:AnyObject] It seems like the automatic morphing is failing you, so it's falling back to a CFString which isn't mappable to AnyObject.
The process becomes a little clearer if we break it up more:
// Recover the original dictionary, and cast is by input and output, to it
// all makes sense. This will allow String as a parameter and return an NSNumber
// as a result.
let userInfo = notification.userInfo as [String:NSNumber]
// From the userInfo, let's extract the raw NSNumber using lookup
let reason = userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]
// Convert the NSNumber into an MPMovieFinishReason enum. Note that it's
// 0215 and I'm on ambien so I don't care about the force unwrapping that
// should be optional unwrapping
let finishReason = MPMovieFinishReason.fromRaw(reason!.integerValue)
Many problems can be broken down into much simpler problems if you just take it a single step at a time. Modern compilers aren't even too bothered by it as the can recognize when variables are no longer in use and do proper reclamation. Also note using let instead of var for those temporary values since they shouldn't be reused anyway.
Try the type-casting function Int()
ie.,
var finishReason = Int(notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]) as MPMovieFinishReason;

Resources