Showing posts with label NSDictionary. Show all posts
Showing posts with label NSDictionary. Show all posts

Wednesday, May 2, 2018

Swift Constrained Extensions


Extension are used to add new functionalities.

  1. An extension can be written on NSArray to remove duplicates.
  2. An extension can be written on NSString to remove unwanted words.
  3. An extension can be written on NSDictionary to remove all null values.


Like this, Not only for Native classes but also for custom classes we can very well write the Extensions.

This sounds interesting and very useful until you come across a scenario where you need extension only for specific type.

Let’s say, We have an array where we need to write an extension to check whether it contains a string or not in it. This is pretty simple, but what If that array can have Ints/Strings/Dictionaries?

So, Here, Based on the type of elements an array is having, we need to write separate extensions for NSArray.











stringArr containsKey goes to Element == String constrained extension as this array is having all strings in it. Where as, intArr containsKey goes to Element: Numeric constrained extension.
Keep a breakpoint and check which array extension is getting called.

That is how constrained extensions are very useful to route logic based on the Elements type in an array.

Here, you might have observed like for String I have given,

Element == String

&

for Ints and Floats, I have given,

Element: Numeric





There is a point here to be discussed.

Element == String, Element should be of String type.
Element: Numeric, Element should confirm to Numeric protocol

That is the reason, intArr and floatArr are going to Numeric constrained extension.



Hope this post is useful. Feel free to comment incase of any queries.

Monday, January 23, 2017

Swift 3.0 Sorting Dictionary based on values

In my Objective C Sorting NSDictionary based on Values tutorial, I have explained Dictionary sorting based on values using Objective C. In this tutorial let's see the same functionality using Swift 3.0.

  
   let isAscending = false

   let dict = [

          "AAAA" : Int(2500),
          "BBBB" : Int(3200),
          "CCCC" : Int(2800),
          "DDDD" : Int(1200)

   ]


I have taken a Dictionary with keys as Strings and values as Ints. I have also taken a flag(isAscending) to configure the order.

  
    let sortedDict = dict.sorted {(_ obj1: (key1: String, value1: Int), 
                                              _ obj2: (key2: String, value2: Int)) -> Bool in
    
         let val1 = (obj1.value1)
         let val2 = (obj2.value2)
    
         if (isAscending) {

             if((val1 < val2)) {
                return true
              }

         }

         else {

             if((val1 > val2)) {
                return true
            }

         }
    
      return false
    
  }


  print (sortedDict)

  isAscending = false  :- [("BBBB", 3200), ("CCCC", 2800), ("AAAA", 2500), ("DDDD", 1200)]
  isAscending = true   :- [("DDDD", 1200), ("AAAA", 2500), ("CCCC", 2800), ("BBBB", 3200)]
       




Hope this post is useful. Feel free to comment incase of any queries.



Friday, December 30, 2016

Objective C Sorting NSDictionary based on Values

We often need to sort the key value pairs based on the value and have the keys to run the show. In this post let’s discuss Dictionary sorting based on values.

  
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",                                                                                                        nil];


I have taken a dictionary which is having key value pairs. The values are numbers. I need to sort(Ascending / Descending) those values and have the sorted keys ready.

The sorting could be Ascending or Descending. So let me take a function and pass my sorting type as shown below.

  
  - (void)sortDict:(BOOL)isAscending {
    
      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",
                                                                                                        nil];
    
      NSArray *sortedKeys = [dict keysSortedByValueUsingComparator: 
                                                                             ^(id obj1, id obj2) {
            if(isAscending){
               return [obj1 compare:obj2];
            }
            else {
                return [obj2 compare:obj1];
            }

       }];
    
      NSLog(@"Sorted Keys: %@",sortedKeys.description);    

  }


Technically we can use keysSortedByValueUsingComparator method of NSDictionary to do this and based on the sorting type passed we need to change the comparison in the block.

  
       if (isAscending) {
           return [obj1 compare:obj2];
       }

       else {
           return [obj2 compare:obj1];
       }



  
 Ascending :

     Sorted Keys: (
     BBBB,
     CCCC,
     AAAA,
     DDDD
     )

 Descending :

     Sorted Keys: (
     DDDD,
     AAAA,
     CCCC,
     BBBB

     )


As simple as that. Now you have your Dictionary keys in your sorted order.


Hope this post is useful. Feel free to comment in case of any queries.


Wednesday, January 13, 2016

Objective C preparing JSON object



We all know that JSON is the most suitable format for to and fro of the data through mobile services. Because, It is light weight and the format is easy to read and write.

In this post let's discuss on how to prepare a JSON object from a list of information whether it's a key based information (NSDictionary) or a index based information (NSArray).

Let's say we have user profile information in a dictionary as shown below.

NSDictionary *userInfoDict = [NSDictionary alloc] initWithObjectsAndKeys:

@"Karunakar",@"firstname",
@"Bandikatla",@"lastname",
@"Male",@"gender",
@"India",@"country",
@"Degree",@"education",

nil];

We need to send the above information to a service. Obviously, we can't send a dictionary object to a service. We need to convert it to string format and on the server side this information should be parsable. So we need to convert it to a JSON string.

Let's see how to convert a dictionary information to a JSON string using Objective C.

Using NSJSONSerialization, we can convert this dictionary to NSData and then we can pass it to service or we can convert this to NSString from NSData and then pass it as a JSON formatted string as shown below.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject: userInfoDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

Sometimes, we may even need to upload user information or some other information as a file to the server. In this case we can directly give NSData to file upload service. We need to check the error value to make sure things are fine before sending it to the server.

Last but not the least, let's see what is that 'options' parameter here. If we are uploading this user info file to the server, If we open that file, If we want that file to be in a JSON readable format like shown below, the option should be NSJSONWritingPrettyPrinted. If you are not bothered about the pretty writing format, you can ignore that parameter.














Hope this post is useful. Feel free to comment incase of any queries.