Queue implementation in swift


public struct Queue<T>{

    private var array:[T]

    public init(){

        array = []

    }

    //MARK: isEmpty

    public var isEmpty:Bool{

        return array.count == 0

    }

    //MARK: count

    public var count:Int{

        return array.count

    }

    //MARK: enqueue

    public mutating func enqueue(element:T){

        array.append(element)

    }

    //MARK: dequeue

    public mutating func dequeue()->T?{

        if isEmpty{

            return nil

        }

        return array.removeFirst()

    }

    //MARK: get Peek element

    public func peek()->T?{

        return array.last

    }

}

// this queue

var myQueue = Queue<Int>()

myQueue.enqueue(10)

myQueue.dequeue()

Advertisements

Common method in Swift


1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false

            }

            

        }

        return true

    }

2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){

 }else{

            return false

        }

      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result

    }

3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {

    

        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)

        }else{

            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)

            alert.show()

           

        }

    }

4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)

    {

        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)

        NSUserDefaults.standardUserDefaults().synchronize()

    }

    

    class func userDefaultForKey(key:String) -> String

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString

        

    }

    class func userDefaultForAny(key:String) -> AnyObject

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!

    }

    

    class func userdefaultForArray(key:String) -> Array<AnyObject>

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array

    }

    

    class func removeFromUserDefaultForKey(key:String)

    {

        NSUserDefaults.standardUserDefaults().removeObjectForKey(key)

        NSUserDefaults.standardUserDefaults().synchronize()

        

    }

5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height

Use HexColor in Swift as a color


Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)

   }

   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)

   }

}

Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

MultiThreading in iOS


Blocks are important in iOS programming because they are used to implement multithreading with GCD (Grand Central Dispatch).  A block is a chunk of code contained in {}.  To indicate the beginning of a block use a caret (^). Here is a block that prints a string.

^{
    NSString *name = "Batman";
    NSLog(@"My name is %@", name);
};

We use the caret (^) character to define the beginning of a block literal, and if there are any arguments they are contained in () followed by the block code itself contained in {}. An example of a block that takes an int as an argument and returns the square value.

^(int value){
    return value*value;
}

You don’t have to declare the return type of a block, it can be inferred from the code in the block. Most of the time we pass the block to a method directly, but we can also assign it to a block variable. The syntax for declaring a block variable is “return_type (^name) (arguments)” If we declare a block variable “square” and assign to it the block we used in the previous example, it would look like this.

int (^square) (int) = ^(int value){
    return value*value;
};

You can call this block just like a function.

int square_value = square(5);

We can also create a type definition for a variable that holds a block by using typedef. The syntax is similar to declaring a block variable name “typedef return_type (^type_name) (arguments)” Then we can declare the block variables with “type_name block_name = ^(arguments){…}”

Blocks are closures, therefore they have access to local variables when the block is created. Local variables are read only. If you want to be able to change the value of local variables, they need to be declared with __block.

To implement multithreading in iOS we use GCD (Grand Central Dispatch). Any operation that takes a long time to execute might lock the UI (User Interface) while it is being performed. For example, anything network related, like getting an image from a remote server. If the image is large enough, it might take a minute or two to download. If we don’t use a different thread for downloading the image, the whole app will be locked for the duration of the time it takes to download the image. In cases like this it is a good idea to use GCD to improve the user experience. This is where blocks become very useful to programmers.

GCD is a C API, therefore it is not object oriented API. The most basic use of GCD is to create a queue, and then to put blocks on that queue to be executed in a different thread by the system. The function used to create a queue and put a block on one are as follows

//to create a queue
dispatch_queue_t dispatch_queue_create(const char *label, NULL);

//to put a block on a queue
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block):

^dispatch_block_t is a prototype of blocks submitted that takes no arguments and doesn’t return anything. Let’s say we have a method that downloads an xml file from the internet.

-(void)fetchXML
{
    NSString *URLString = @"example.com/example.xml";
    NSURL *URL = [NSURL URLWithString:[URLString
                        stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    NSData *dataXML = [NSData dataWithContentsOfURL:URL];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:dataXML];
    [xmlParser setDelegate:self];
    BOOL success = [xmlParser parse];
    // test the result
    if (success) {
        NSLog(@"No errors");
    } else {
        NSLog(@"Error");
    }
}

To execute the fetching of the file on a different thread, we need to do the following modifications to our code. Create a queue and then put the code as a block on that queue.

-(void)fetchXML
{
    dispatch_queue_t fetchQueue = dispatch_queue_create("fetch xml", NULL);
    dispatch_async(fetchQueue, ^{
        NSString *URLString = @"example.com/example.xml";
        NSURL *URL = [NSURL URLWithString:[URLString
                         stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
        NSData *dataXML = [NSData dataWithContentsOfURL:URL];
        NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:dataXML];
        [xmlParser setDelegate:self];
        BOOL success = [xmlParser parse];
        // test the result
        if (success) {
            NSLog(@"No errors");
        } else {
            NSLog(@"Error");
        }
   });
}

There is just one more rule about using GCD for multithreading. When we have code that makes changes to UIKit objects, we need to dispatch that block of code in the main queue. The way to get the main queue is with “dispatch_get_main_queue”.

dispatch_async(dispatch_get_main_queue(), ^{....});

This will get you started with GCD. There are a lot more functions that you can use in GCD, consult the apple docs for more details on more advanced uses of GCD.

 

<script type=”text/javascript”>
(function() {
window._pa = window._pa || {};
// _pa.orderId = “myOrderId”; // OPTIONAL: attach unique conversion identifier to conversions
// _pa.revenue = “19.99”; // OPTIONAL: attach dynamic purchase values to conversions
// _pa.productId = “myProductId”; // OPTIONAL: Include product ID for use with dynamic ads
var pa = document.createElement(‘script’); pa.type = ‘text/javascript’; pa.async = true;
pa.src = (‘https:’ == document.location.protocol ? ‘https:’ : ‘http:’) + “//tag.perfectaudience.com/serve/529ebd713c619f6dda00000d.js”;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(pa, s);
})();
</script>

Asynchronous Operations in iOS with Grand Central Dispatch


Grand Central Dispatch, or GCD for short, is a C API that makes it exceptionally easy to perform asynchronous operations in iOS. Asynchronous operations are a fundamental part of every iOS app when you want to perform long operations without freezing or blocking the user interface. You can image that if your entire app froze without warning then your users would get quite irritated.

With GCD, you can line up blocks of code in a queue for the system to execute as necessary. These blocks or operations, will be dispatched in the queue to another thread, leaving your main UI thread to continue its tasks. It’s important to know that GCD will use separate threads for it’s operations but which thread it isn’t important to you. All that matters is that your long running process in a separate thread outside the main thread where your UI and gestures are running.

GCD queues can be concurrent or serial but serial queues (where there is one queue and each item is executed one after the other in order) are easier to understand so we’ll look at those.

The more important functions you’ll need are for creating the queue:

dispatch_queue_t dispatch_queue_create(const char *label, dispatch_queue_attr_t attr);

and adding blocks to the queue:

void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

There’s also a couple helper functions for retrieving specific queues such as:

dispatch_queue_t dispatch_get_current_queue(void);
dispatch_queue_t dispatch_get_main_queue(void);

The dispatch_get_current_queue function will return the current queue from which the block is dispatched and the dispatch_get_main_queue function will return the main queue where your UI is running.

The dispatch_get_main_queue function is very useful for updating the iOS app’s UI as UIKit methods are not thread safe (with a few exceptions) so any calls you make to update UI elements must always be done from the main queue.

A typical GCD call would look something like this:

// Doing something on the main thread

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI

    });
}); 

// Continue doing other stuff on the 
// main thread while process is running.

GCD relies on block so it has a really nice, readable syntax. It becomes clear what happes in the background thread and the main thread. For example, here’s how you might load a few images:

NSArray *images = @[@"http://example.com/image1.png",
                 @"http://example.com/image2.png",
                 @"http://example.com/image3.png",
                 @"http://example.com/image4.png"];

dispatch_queue_t imageQueue = dispatch_queue_create("Image Queue",NULL);

for (NSString *urlString in images) {
    dispatch_async(imageQueue, ^{

        NSURL *url = [NSURL URLWithString:urlString];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:imageData];

        NSUInteger imageIndex = [images indexOfObject:urlString];
        UIImageView *imageVIew = (UIImageView *)[self.view viewWithTag:imageIndex];

        if (!imageView) return;

        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI
            [imageVIew setImage:image];
        });

    }); 
}

// Continue doing other stuff while images load.

You’ll notice I check for imageView before dispatching to the main thread. This avoids the main queue dispatch if the network request took a long time and the imageView is no longer there for one reason or another. Once a block has been dispatched onto a queue, it’s not possible to stop it. The block will execute to completion and there’s nothing you can do. If you have a very long running process, such as loading a URL, you should add logic between each step to check to see if it should continue and if it’s still appropriate to finish the operation.

That’s it. Start build queues and making your UI more responsive.

Aside: Concurrency

If you want to run a single independent queued operation and you’re not concerned with other concurrent operations, you can use the global concurrent queue:

dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

This will return a concurrent queue with the given priority as outlined in the documentation:

DISPATCH_QUEUE_PRIORITY_HIGH Items dispatched to the queue will run at high priority, i.e. the queue will be scheduled for execution before any default priority or low priority queue.

DISPATCH_QUEUE_PRIORITY_DEFAULT Items dispatched to the queue will run at the default priority, i.e. the queue will be scheduled for execution after all high priority queues have been scheduled, but before any low priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_LOW Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after all default priority and high priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_BACKGROUND Items dispatched to the queue will run at background priority, i.e. the queue will be scheduled for execution after all higher priority queues have been scheduled and the system will run items on this queue on a thread with background status as per setpriority(2) (i.e. disk I/O is throttled and the thread’s scheduling priority is set to lowest value).

from queue.h