Tuesday, March 10, 2015

How to create custom operators in Swift?

In Swift, you can create your own custom operators in additions to the Swift operators. 

Swift has Unary, Binary and Ternary Operators. You can create the custom operators for Unary and Binary operators. For Unary operators, you can use Prefix and Postfix modifier and for Binary Operator, you can use Infix modifier.

Currently, we cannot write the Custom Ternary operators. Swift has only one Ternary Operator that is Condition operator.
eg- a ? b: c

Following are the modifier which you can use to create the custom operators. 

Prefix- A Unary Operator that is placed before the operand.
eg- b = ++a (++ is operator and a is operand)

Postfix- A Unary Operator that is placed after the operand.
eg- b = a++

Infix- A Binary operator that is placed in between the two operands.
eg- c = a + b

You can create the custom operators that starts with one of the ASCII characters /, =, -, +, !, *, %, <, >, &, |, , or ~, or any of the Unicode characters in the "Math Symbols" character set.

Note-  As mentioned in the Apple documentation, there are some operators which can’t be overloaded nor can be used as Custom Operators. 
The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.

Implementing a Prefix and postfix operator-

As you know that Unary operator operates on single operand. It can be Prefix (++a) if they precede the operand or Postfix (a++) if they follows the operand.

You can implement your own custom unary operators by preceding the operators function with the prefix and postfix modifier.

Let’s declare the +++  prefix operator which can doubles the operand’s value.

prefix operator +++ {}

Now, define the operator functions.

prefix func +++ (number: Double) -> Double {
    return (number + number)
}

let value = +++10 // 20

In the same way, you can create the unary operator with  the postfix modifier.




Implementing an Infix Operator- 

Infix operator is operates on two operators and placed in between the two operands. When you declare the custom Infix operators you can specify the Associativity and Precedence. 

If there are two or more infix operators in the expressions then on the basis of Associativity and Precedence, it can be define which infix operator executes first.

Here, we have define the new custom infix operator +- with left associativity and 140 precedence.

Associativity value can be left, Right and None. By default it is None and the precedence value is 100 if it is not specified. 

infix operator +- { associativity left precedence 140 }

Now, implements the +- operator which returns the tuple value of sum and difference of two operands.

func +- (left: Double, right: Double) -> (Double, Double) {
    return (left + right, left - right)
}

let value = 3 +- 2 // (5, 1)






Tuesday, February 24, 2015

Subscript in Swift

Subscript are the shortcut to access the elements from collection, sequence and list. You can define the subscript in Class, Struct and enumeration to set and get the value by index. By using Subscript, you don’t need to write the separate methods for getting and setting the values.


Subscript can  read- write or read only. You define subscript by using the subscript keyword and specify one or more input parameters and return type.

subscript(parameters) -> ReturnType {
    get {
        //return someValue
    }
    set (newValue) {
        //setSomeValue()
    }
}

For read only Subscript, you can drop the get keyword.

subscript(parameters) -> ReturnType {
        //return someValue
}

Here, we have created the subscript in String Extension to check the substring is found in String or not. This Subscript will return a true value if substring is found in the String. This is the Read Only subscript.

extension String {
    
    subscript(pattern: String) -> Bool {
            let range = self.rangeOfString(pattern)
            return (range != nil)
    }
}

   var str = "Hello Swift"
   println(str["Swift"]) // true


Let’s create another Subscript of Read-Write type. In this Subscript, we can replace the Substring with another substring. Also, you can check that String contains substring or not. If the String contains the Substring, it will return the substring otherwise nil.

extension String {
    
    subscript(pattern: String) -> String? {
        get {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                return pattern
            } else {
                return nil
            }
        }
        set(replacement) {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                self = self.stringByReplacingCharactersInRange(range!, withString: replacement!)
            }
        }
    }
}


var str = "Hello Swift"
println(str["Swift"]) // Swift
println(str["Java"]) // nil

// Replace Hello with Hi
str["Hello"] = "Hi"
println(str)

In the setter, you can use the newValue keyword in place of replacement and code look like this.

subscript(pattern: String) -> String? {
        get {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                return pattern
            } else {
                return nil
            }
        }
        set {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                self = self.stringByReplacingCharactersInRange(range!, withString: newValue!)
            }
        }
    }

Wednesday, February 11, 2015

Alternative of #pragma mark for Swift


In Objective C, you might have used the #pragma mark directive for code organization in Jump bar.
But with Xcode 6 there is no pragma directive. Instead of this, you can use MARK, TODO and FIXME for managing the code which is supported by Xcode 6.

1) MARK:- It is an alternative of #pragma mark directive. It can be used for organizing code in a logical way so that it can be navigated by jump bar.




2) TO DO:- You can use this tag to make reminder to work on this later. You can use this tag within the function or outside the function.




3) FIX ME:- You can use this tag to make a reminder to fix some piece of code or methods. It can be placed inside or outside of the methods.




Note- “-” is optional in all the directives. If you use this dash then it will show a separator line in the Jump bar above the text.

Monday, February 2, 2015

Generic Functions in Swift.


Generic is one of the powerful feature of Swift. Most of the Swift Standard library uses this feature.

For instance, Swift Array and Dictionary are Generics Collection which can hold the value of any Type. You can create the array which holds Int values or String values.

With Generics code, developer can write flexible and reusable function which can work with any Type.

Suppose you have to write a function to swap two Int values. 



In Swift, parameters are passed by value so you can’t change the parameters value within the Function. If you want to modify the parameters value then you have to define the parameters as inout.

When you call a  function with an inout parameters, you use ampersand (&). This is something like passing the address of values as we have in C language.

If you want to write a function which can swap String or Doubles values then your function will look like this.





You may have noticed that all these functions bodies are same. Only difference is the type of the value passed to this functions.

So, you can write Generics functions which can work with any Type.




Generics function uses a placeholder type in angular bracket instead of actual Type name (Int, String). Both parameter a and b must be of same T type whatever T represents. 






Thursday, January 29, 2015

How to open Share and Action Extension from your application?


With the introduction of Extension in iOS 8, many applications is available with Share and Action Extension and if we want to share content and perform some action from our application to those app then we can open the extensions of those application using UIActivityViewController.

UIActivityViewController is a standard view controller which can offers System specific services such as copying items to the pasteboard, posting content to social media sites, sending items via email or SMS from your application.

Below is the code to initiate UIActivityViewController.

let text = "Text to share"
        let url : AnyObject! = NSURL(string: "https://www.google.co.in")
        let image : AnyObject = UIImage(named:"download.jpeg")!
        let activityItems : [AnyObject] = [text, url, image]
        
        let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        self.presentViewController(activityViewController, animated: true, completion: nil)


Here, we have created array of AcitivityItems(image, text, url) and passed it to the UIActivityViewController Constructor.

This will show all the Share and Action Extension supported by the system or application which are installed in your devices.




Note- User can manually enable and disable the application by tapping the More shown in the Share and Action Activity section. User can also reorder this activities.



     
There are 2 types of activities- Share and Action. Following are the activities for which system has built in supports-

 UIActivityTypePostToFacebook;
 UIActivityTypePostToTwitter;
 UIActivityTypePostToWeibo;
 UIActivityTypeMessage;
 UIActivityTypeMail;
 UIActivityTypePrint;
 UIActivityTypeCopyToPasteboard;
 UIActivityTypeAssignToContact;
 UIActivityTypeSaveToCameraRoll;
 UIActivityTypeAddToReadingList;
 UIActivityTypePostToFlickr;
 UIActivityTypePostToVimeo;
 UIActivityTypePostToTencentWeibo;
 UIActivityTypeAirDrop;

By Default, UIActivityViewController will show all the available activities. If you want to exclude any of the activity from your application then you can do this by passing the array of activities which you want to exclude to excludedActivityTypes property of UIActivityViewController.

        activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop];

Here, we have excluded AirDrop to be shown in our application.




You can also check when the activity has been completed by calling completionWithItemsHandler.

 activityViewController.completionWithItemsHandler = {
            (activity, success, items, error) in
            println("Activity: \(activity) Success: \(success) Items: \(items) Error: \(error)")
        }

This is the complete method which you can use in your application and connect the action with the Button.
  
    @IBAction func shareAction(sender: AnyObject) {
        
        let text = "Text to share"
        let url : AnyObject! = NSURL(string: "https://www.google.co.in")
        let image : AnyObject = UIImage(named:"download.jpeg")!
        let activityItems : [AnyObject] = [text, url, image]
        
        let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop];
        self.presentViewController(activityViewController, animated: true, completion: nil)
        
        activityViewController.completionWithItemsHandler = {
            (activity, success, items, error) in
            println("Activity: \(activity) Success: \(success) Items: \(items) Error: \(error)")
        }
        
    }


Download the complete Project from here.

Monday, January 19, 2015

How to use both Objective C and Swift in same Project


With the introduction of new language Swift, developers can use this language to develop the iOS project. But most of the APIs are available in Objective C. So if any developer is developing the project in Swift language and they wants to use these Objective C API in there project then they can do it.

Even Developers can create the project with mix and match of both languages Objective C and Swift.

This post will tell you how you can use both language in the application.


Use Objective C in Your Swift project-

If you want to use Swift file in your Objective C project, just create a Objective C file and Xcode will prompt you asking “Would you like to create Objective C Bridging Header?”





When you tap on Yes it will create a Bridging Header file with name "ProductName-Bridging-Header.h"

You can import your Objective C code to Swift by importing your header file in this Bridging header file.





Use Swift in Your Objective-C project-


In order to use Swift file in your Objective C project, just create a Swift file by selecting File> New > Swift.



Now Xcode will prompt you asking “Would you like to create Objective C Bridging Header?”
 You can import your Swift code to any Objective C file by using this syntax-

#import “ProjectName-Swift.h”



You can download the sample app from Github.



Tuesday, November 18, 2014

Today Extension in Swift


Today Extension also known as widget and its appear in the notification centre. It is used to show some quick information or to perform some quick task.

In this Tutorial, you will learn how to create Today extension and sharing data between containing app and Extension.  Also, you will learn how to open the containing app from Today Extension.

Create Today Extension-

Create a project with “Single View Application” template  and select languages as Swift and set the project name “TodayExtensionSample”.





Add Target-

In the Xcode project navigator, select the project and add new target to the project. Choose TodayExtension in Application Extension and named it “Photo Extension”. Also make sure that you have select the language Swift for both Project and Extension. 



This target will comprises of 3 files- 
1) TodayViewController.swift
2) MainInterface.storyboard 
3) Info.plist

TodayViewController.swift is subclass of UIViewController & adopting the NCWidgetProviding protocol and includes the method-

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!)

This method is called to give an opportunity to update the contents of Widget and redraw its view before taking snapshot.When the widget is finished updating its contents, it should call the completion handler block and pass the appropriate NCUpdateResult value.


Run Extension-

Now, if you run your extension then it will gives you the option to run the host app. Choose Today and it will launch the Today Notification centre  & your extension is showing Hello World.



In the notification centre there is a button Edit. When you tap on it, it will show all the available Today Extension. From here, you can enable & disable the extension. Also, you can recorder them.




Design User Interface-

Add a label & button named ”Open” in your extension with appropriate Constraints.

Note- Always use Autolayout for designing your Extension layout.  

Add a textfield & button named “Done” in the View Controller of your Containing App with appropriate Constraints. 

I have added the textField in Containing app so that user can enter some number in textField & when user taps on Done button, i have saved it to user Defaults and when user sees the Widget in Extension, i will show this number and user can open the Containing app by tapping the Open Button in Extension.


Share Data-

You can share the data between containing app & extension using App Group. You need to enable the AppGroup in both application & Extension.

To enable the App Group, select the project Navigation and choose your Application target  and taps on Capability from the top Menu and turns on the AppGroup.




Now, select your Development Team to use for provisioning and click Choose. It will add the “App Groups” entitlement to your App ID. You can add the New Group or choose from the existing one. I have given the Group name “ group.CompanyName.TodayExtension” in my sample app.




Now Repeat the same process for your Extension & choose the same AppGroup which you have selected for your application.


Note- AppGroup Name should be Unique.

Application code-

Select Your View Controller and implement the Done button-

@IBAction func doneButtonPressed (sender: UIButton){
if (textField?.isFirstResponder() != nil){
textField?.resignFirstResponder()
}
if  textField?.text.utf16Count > 0 {
var userDefaults: NSUserDefaults = NSUserDefaults(suiteName: "group.companyName.todayExtensionSample")
userDefaults.setObject(textField?.text, forKey:"Score")
userDefaults.synchronize()
}
}

Here, we have initialised the user Defaults with AppGroup & save the number entered in the textfield in the user Defaults.


Extension Code -

Now, open the TodayViewController and add this code in ViewDidLoad & widgetPerformUpdateWithCompletionHandler.

var userDefaults: NSUserDefaults = NSUserDefaults(suiteName: "group.companyName.todayExtensionSample")
var score = userDefaults.objectForKey("Score")! as? String ?? "0"
println("\(score)")
scoreLabel?.text = "Score- \(score)"

Here, again we have initialised the user Defaults with AppGroup & access the same value which we have saved from the Application.


Open App from Extension-

You can open the containing app from Widget by using openURL:completionHandler: method of NSExtensionContext. This method will work only for Today Extension. So you can 

openURL:completionHandler: method of NSExtensionContext to tell the system to open its containing app.

To open the application from your extension-

1) In the project Navigation,select the Application target & choose Info from the Top Menu.

2) Set the custom UrlScheme “todayExtensionSample”.

3) Implement the Open button in your TodayViewComntroller.

@IBAction func openButtonPressed(){
var url =  NSURL(string:"todayExtensionSample://")
self.extensionContext?.openURL(url, completionHandler:{(success: Bool) -> Void in
println("task done!")
})
}


Now, run your application and enter some number in the Text field and taps the Done Button. Now run your Extension, it will show the same Number which you have save in your application.

If you taps the Open Button, it will open your Application. 




You can download the sample app from Github.