Wednesday, 18 November 2015

Higher Order Functions: Map, Filter, Reduce and more

The code in this post was written in Xcode 6 beta 5. It may not work in future releases of Xcode without changes. All code examples are using Swift’s trailing closure syntax.
For-in-loops are often used to iterate through an array of objects, modifying another object with each iteration. For example, looping through an array of numbers in order to create a new array of numbers formatted as strings:

let numbers = [ 10000, 10303, 30913, 50000, 100000, 101039, 1000000 ]
var formattedNumbers: [String] = []  
for number in numbers {
    let formattedNumber =
          NSNumberFormatter.localizedStringFromNumber(number, numberStyle: .DecimalStyle)
   formattedNumbers.append(formattedNumber)
}

// [ "10,000", "10,303", "30,913", "50,000", "100,000", "101,039", "1,000,000" ]


With Swift, iOS and Mac developers have map, filter, and reduce methods on arrays. In my experience, these methods can replace almost all uses of for-in-loops, and are more clear and concise.

Map

The map method takes a function (transform), and returns an array containing the results of calling transform on each element in the array. The example above could be written like this:

let formattedNumbers = numbers.map {
            NSNumberFormatter.localizedStringFromNumber
                                             ($0, numberStyle: .DecimalStyle)
   }

// [ "10,000", "10,303", "30,913", "50,000", "100,000", "101,039", "1,000,000" ]

Filter

The filter method takes a function (includeElement) which, given an element in the array, returns a Bool indicating whether the element should be included in the resulting array. For example, removing all the odd numbers from the numbers array could be done like this:

let evenNumbers = numbers.filter { $0 % 2 == 0 }  

// [ 10000, 50000, 100000, 1000000 ]

Reduce

The reduce method reduces an array into a single value. It takes two parameters: a starting value, and a function which takes a running total and an element of the array as parameters, and returns a new running total. For example, getting the sum of all the numbers in an array could be done like this:

let total = numbers.reduce(0) { $0 + $1 }  

// 1302255 

Chaining

These three methods can be very powerful, especially when they are chained. For example, given an array of numbers, we can filter out all odd numbers, map the remaining numbers into strings using NSNumberFormatter, and reduce those strings into one string, with a formatted number on each line:

let evenNumbersAsString = numbers
       .filter { $0 % 2 == 0 }
       .map { NSNumberFormatter.localizedStringFromNumber($0, numberStyle: .DecimalStyle) }
       .reduce("") { countElements($0) == 0 ? $1 : $0 + "\n" + $1 }

// "10,000\n50,000\n100,000\n1,000,000"

Monday, 9 February 2015

Nil Coalescing Operator Swift

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil coalescing operator is shorthand for the code below:

a​ != ​nil​ ? ​a​! : ​b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.


NOTE

If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

The example below uses the nil coalescing operator to choose between a default color name and an optional user-defined color name:

let defaultColorName = "red"
var userDefinedColorName: String?     // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName

// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

The userDefinedColorName variable is defined as an optional String, with a default value of nil. Because userDefinedColorName is of an optional type, you can use the nil coalescing operator to consider its value. In the example above, the operator is used to determine an initial value for a String variable called colorNameToUse. Because userDefinedColorName is nil, the expression userDefinedColorName ?? defaultColorName returns the value of defaultColorName, or "red".

If you assign a non-
nil value to userDefinedColorName and perform the nil coalescing operator check again, the value wrapped inside userDefinedColorName is used instead of the default:

userDefinedColorName = "green"
 colorNameToUse = userDefinedColorName ?? defaultColorName

// userDefinedColorName is nil, so colorNameToUse is set to the default of "green" 

Sunday, 3 August 2014

Swift Interview Questions :iOS

What is Swift ?

-----> Swift is a new programming language for iOS and Mac application development. If you are developing an application using swift, you don't need a main function, you don't need to write semicolon at the end of each line.

Swift PlayGround ?

-----> Swift playground is like an instance Feedback. The code written in playground will be resulted in right side in the play ground. It is easy for the developers to get the instance result of their code without running the whole application.

Swift Performance ?

-----> There are various things that has been eliminated from the Swift, like Allocation, Synthesization, Initialization of the object, which we used to do in Objective C. There is no separate file for interface and implementation.

Swift Modern ?

-----> Swift is modern because it supports many concepts like Generics, Closures, Type Interface, Name Space, Multiple return Type, Enums, String Interpolation, Protocols etc. Swift doesn't support pointer concept.

Swift Memory Management ?

-----> Swift uses ARC(Automatic Reference Counting) to manage your application memory. In Swift, ARC automatically frees up the memory used by the class objects, when those objects are no longer used.

Monday, 28 July 2014

Having Swift and Objective C in a same project

Mix and Match Overview:

Objective C and Swift files can coexist in a single project, whether the project was originally an Objective -C or Swift project. This natural workflow makes creating mixed-language app and framework targets as straight forward as creating an app or framework target written in a single language.


The process for working with mixed-language targets differs slightly depending on whether you're writing an app or a framework. The general import model for working with both languages within the same target is depicted below and described in more detail in the following sections.

              image: ../Art/DAG_2x.png

Importing Objective-C into Swift:
To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.
                         image: ../Art/bridgingheader_2x.png

If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding "-Bridging-Header.h". For information on the product module name, see Naming Your Product Module.

You'll need to edit this file to expose your Objective-C code to your Swift code.

To import Objective-C code into Swift from the same target
  
1. In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift. For example:

    Objective-C

    i.   #import "XYZCustomCell.h"
    ii.  #import "XYZCustomView.h"
    iii. #import "XYZCustomViewController.h"

2. Under Build Settings, make sure the Objective-C Bridging Header build setting under Swift Compiler - Code Generation has a path to the header.

The Path should be relative to your project, similar to the way your info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

Any public Objective-C headers listed in this bridging header file will be visible to Swift. The Objective-C functionality will be available in any Swift file within that target automatically, without any import statements. Use your custom Objective-C code with the same Swift syntax you use with system classes.


     Swift
  1.   let myCell = XYZCustomCell( )
  2.   myCell.subTitle = "A custom cell"


DHARANI KUMAR REDDY A

Tuesday, 8 July 2014

Calling a Method in iOS Swift: Takes and Returns multiple values





A function type can have a variadic parameter as the last parameter in its parameter type. Syntactically, a variadic parameter consists of a base type name followed immediately by three dots (...), as in Int.... A variadic parameter is treated as an array that contains elements of the base type name. For instance, the variadic parameter Int... is treated as [Int]. For an example that uses a variadic parameter, see Variadic Parameters.

To specify an in-out parameter, prefix the parameter type with the inout keyword. You can’t mark a variadic parameter or a return type with the inout keyword. In-out parameters are discussed in In-Out Parameters.

The type of a curried function is equivalent to a nested function type. For example, the type of the curried function addTwoNumbers()() below is (Int, Int) -> (Int, NSString, Int):

// Method Declaration in Swift Language:
func addTwoNumbers(a: Int, b: Int) -> (Int, NSString, BOOL)
{ 
return ((a + b), "Addition", True)
}

// Method Calling in Swift Language:
var (value, strValue, isTrue) = addTwoNumbers(4, 5) // Returns 9,Addition and TRUE





Wednesday, 25 June 2014

Getting Started with Swift Language: A Brief Introduction of the New Programming Language

Along with the announcement of iOS 8 and Yosemite, Apple surprised all developers in the WWDC by launching a new programming language called Swift. At AppCoda, we’re all excited about the release of Swift. We enjoy programming in Objective-C but the language has showed its age (which is now 30 years old) as compared to some modern programming languages like Ruby. Swift is advertised as a “fast, modern, safe, interactive” programming language. The language is easier to learn and comes with features to make programming more productive. It seems to me Swift is designed to lure web developers to build apps. The syntax of Swift would be more familiar to web developers. If you have some programming experience with Javascript (or other scripting languages), it would be easier for you to pick up Swift rather than Objective-C.
If you’ve watched the WWDC keynote, you should be amazed by an innovative feature calledPlaygrounds that allow you to experiment Swift and see the result in real-time. In other words, you no longer need to compile and run your app in the Simulator. As you type the code in Playgrounds, you’ll see the actual result immediately without the overheads of compilation.

At the time of this writing, Swift has only been announced for a week. Like many of you, I’m new to Swift. I have downloaded Apple’s free Swift book and played around with Swift a bit. Swift is a neat language and will definitely make developing iOS apps more attractive. In this post, I’ll share what I’ve learnt so far and the basics of Swift.

Variables, Constants and Type Inference:

In Swift, you declare variables with the “var” keyword and constants using the “let” keyword. Here is an example:



These are the two keywords you need to know for variable and constant declaration. You simply use the “let” keyword for storing value that is unchanged. Otherwise, use “var” keyword for storing value that can be changed.
What’s interesting is that Swift allows you to use nearly any character for both variable and constant names. You can even use emoji character for the naming:

Tip: You may wonder how you can type emoji character in Mac OS. It’s easy. Just press Control-Command-spacebar and an emoji picker will be displayed.

You may notice a huge difference in variable declaration between Objective C and Swift. In Objective-C, developers have to specify explicitly the type information when declaring a variable. Be it an int or double or NSString, etc.


It’s your responsibility to specify the type. For Swift, you no longer needs to annotate variables with type information. It provides a huge feature known as Type inference. The feature enables the compiler to deduce the type automatically by examining the values you provide in the variable.


It makes variable and constant declaration much simpler, as compared to Objective C. Swift provides an option for you to explicitly specify the type information if you wish. The below example shows how to specify type information when declaring a variable in Swift:


No Semicolons:

In Objective C, you need to end each statement in your code with a semicolon. If you forget to do so, you’ll end up with a compilation error.
As you can see from the above examples, Swift doesn’t require you to write a semicolon (;) after each statement, though you can still do so if you like.

Basic String Manipulation:

In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants:

In Objective C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make such choice in Swift. Whenever you assign a string as variable (i.e. var), the string can be modified in your code.
Swift simplifies string manipulating and allows you to create a new string from a mix of constants, variables, literals, as well as, expressions. Concatenating strings is super easy. Simply add two strings together using the “+” operator:

Swift automatically combines both messages and you should the following message in console. Note that println is a global function in Swift to print the message in console.


You can do that in Objective C by using stringWithFormat: method. But isn’t the Swift version more readable?

String comparison is more straightforward. In Objective C, you can’t use the == operator to compare two strings. Instead you use the isEqualToString: method of NSString to check if both strings are equal. Finally, Swift allows you to compare strings directly by using the == operator.

Arrays:

The syntax of declaring an array in Swift is similar to that in Objective C. Here is an example:
Objective C:

Swift:


While you can put any objects in NSArray or NSMutableArray in Objective C, arrays in Swift can only store items of the same type. Say, you can only store strings in the above string array. With type inference, Swift automatically detects the array type. But if you like, you can also specify the type in the following form:


Like NSArray, the Swift provides various methods for you to query and manipulate an array.
Simply use the count method to find out the number of items in the array:

In Objective C you use the addObject: method of NSMutableArray to add a new item to an array. Swift makes the operation even simpler. You can add an item by using the “+=” operator:


This applies when you need to add multiple items:


To access or change a particular item in an array, pass the index of the item by using subscript syntax just like that in Objective C.


One interesting feature of Swift is that you can use “…” to change a range of values. Here is an example:


This changes the item 2 to 4 of the recipes array to “Cheese Cake”, “Greek Salad” and “Braised Beef Cheeks”.

Dictionaries:

Swift only provides two collection types. One is arrays and the other is dictionaries. Each value in a dictionary is associated with a unique key. If you’re familiar with NSDictionary in Objective C, the syntax of initializing a dictionary in Swift is quite similar. Here is an example:
Objective C:

Swift:


The key and value in the key-value pairs are separated by a colon. Like array and other variables, Swift automatically detects the type of the key and value. However, if you like, you can specify the type information by using the following syntax:


To iterate through a dictionary, use the for-in loop.


You can also use the keys and values properties to retrieve the keys and values of the dictionary.


To access the value of a particular key, specify the key using the subscript syntax. If you want to add a new key-value pair to the dictionary, simply use the key as the subscript and assign it with a value like below:

Now the companies dictionary contains a total of 5 items. The “TWTR”:”Twitter Inc” pair is automatically added to the companies dictionary.

Classes:

In Objective C, you create separate interface (.h) and implementation (.m) files for classes. Swift no longer requires developers to do that. You can define classes in a single file (.swift) without separating the external interface and implementation.
To define a class, you use the class keyword. Here is a sample class in Swift:
Similar to Objective C, right? In the above example, we define a Recipe class with three properties including name duration and ingredients. Swift requires you to provide the default values of the properties. You’ll end up with compilation error if the initial values are missing.
What if you don’t want to assign a default value? Swift allows you to write a question mark (?) after the type of a value to mark the value as optional.

In the above code, the name and ingredients properties are automatically assigned with a default value of nil. To create an instance of a class, just use the below syntax:




You use the dot notation to access or change the property of an instance.




Swift allows you to subclass Objective-C classes and adopt Objective-C protocols. For example, you have a SimpleTableViewController class that extends from UIViewController class and adopts both UITableViewDelegate and UITableViewDataSource protocols. You can still use the Objective C classes and protocols but the syntax is a bit different.
Objective C:

Swift:


Methods:

Swift allows you to define methods in class, structure or enumeration. I’ll focus on instance methods of a class here. You can use the func keyword to declare a method. Here is a sample method without return value and parameters:
In Objective C, you call a method like this:



In Swift, you call a method like this:



If you need to declare a method with parameters and return values, the method will look this:



The syntax looks a bit awkward especially for the -> operator. The above method takes a name parameter in String type as the input. The -> operator is used as an indicator for method with a return value. In the above code, you specify a return type of Int that returns the total number of todo items. Below demonstrates how you call the method:




Control Flow:

Control flow and loops employ a very C-like syntax. As you can see above, Swift provides for-in loop to iterate through arrays and dictionaries. You can use if statement to execute code based on a certain condition. Here I’d just like to highlight the switch statement in Swift which is much powerful than that in Objective C. Take a look at the following sample switch statement. Do you notice anything special?


Yes, switch statement can now handle strings. You can’t do switching on NSString in Objective C. You had to use several if statements to implement the above code. At last Swift brings us this most sought after utilization of switch statement.
Another enhancement of switch statement is the support of range matching. Take a look at the below code:


The switch cases now lets you check values within a certain range by using two new operators: “…” and “..”. Both operators serve as a shortcut for expressing a range of values.
Consider the sample range of “41…70″, the … operator defines a range that runs from 41 to 70, including both 41 and 70. If we use the .. operator instead of … in the example, this defines a range that runs from 41 to 69. In other words, 70 is excluded from the range.
Please do post your comments.

DHARANI KUMAR REDDY A

Tuesday, 6 May 2014

Beginning Auto Layout Tutorial in iOS 7

The problem with springs and struts

You are no doubt familiar with autosizing masks – also known as the “springs and struts” model. The autosizing mask determines what happens to a view when its superview changes size. Does it have flexible or fixed margins (the struts), and what happens to its width and height (the springs)?
For example, with a flexible width the view will become proportionally wider if the superview also becomes wider. And with a fixed right margin, the view’s right edge will always stick to the superview’s right edge.
The autosizing system works well for simple cases, but it quickly breaks down when your layouts become more intricate. Let’s look at an example where springs and struts simply don’t cut it.
Open Xcode 5 and create a new iPhone project based on the Single View Application template. Call the app “StrutsProblem”:

Click on Main.storyboard to open it in Interface Builder. Before you do anything else, first disable Auto Layout for this storyboard. You do that in the File inspector, the first of the six tabs:

























Uncheck the Use Autolayout box. Now the storyboard uses the old struts-and-springs model.

Note: Any new nib or storyboard files that you create with Xcode 4.5 or better will have Auto Layout activated by default. Because Auto Layout is an iOS 6-and-up feature only, if you want to use the latest Xcode to make apps that are compatible with iOS 5, you need to disable Auto Layout on any new nibs or storyboard files by unchecking the “Use Autolayout” checkbox.

Drag three new views onto the main view and line them up like this:













For clarity, give each view its own color so that you can see which is which.
Each view is inset 20 points from the window’s borders; the padding between the views is also 20 points. The bottom view is 280 points wide and the two views on top are both 130 points wide. All views are 254 points high.
Run the app on the iPhone Retina 4-inch simulator and rotate the simulator to landscape. That will make the app look like this, not quite what I had in mind:








Note: You can rotate the simulator using the Hardware\Rotate Left and Rotate Right menu options, or by holding down  on your keyboard and tapping the left or right arrow keys.
Instead, you want the app to look like this in landscape:








Obviously, the autosizing masks for all three views leave a little something to be desired. Change the autosizing settings for the top-left view to:
This makes the view stick to the top and left edges (but not the bottom and right edges), and resizes it both horizontally and vertically when the superview changes its size.
Similarly, change the autosizing settings for the top-right view:
And for the bottom view:
Run the app again and rotate to landscape. It should now almost look like this:








Close, but not quite. The padding between the views is not correct. Another way of looking at it is that the sizes of the views are not 100% right. The problem is that the autosizing masks tell the views to resize when the superview resizes, but there is no way to tell them by how much they should resize.
You can play with the autosizing masks – for example, change the flexible width and height settings (the “springs”) – but you won’t get it to look exactly right with a 20-point gap between the three views.
To solve this layout problem with the springs and struts method, unfortunately you will have to write some code.
UIKit sends several messages to your view controllers before, during and after rotating the user interface. You can intercept these messages to make changes to the layout of your UI. Typically you would override viewWillLayoutSubviews to change the frames of any views that need to be rearranged.
Before you can do that, you first have to make outlet properties to refer to the views to be arranged.
Switch to the Assistant Editor mode (middle button on the Editor toolset on the Xcode toolbar) and Ctrl-drag from each of the three views onto ViewController.m:

Connect the views to these three properties, respectively:
@property (weak, nonatomic) IBOutlet UIView *topLeftView;
@property (weak, nonatomic) IBOutlet UIView *topRightView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

Add the following code to ViewController.m:
- (void)viewWillLayoutSubviews
{
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
    {
        CGRect rect = self.topLeftView.frame;
        rect.size.width = 254;
        rect.size.height = 130;
        self.topLeftView.frame = rect;
 
        rect = self.topRightView.frame;
        rect.origin.x = 294;
        rect.size.width = 254;
        rect.size.height = 130;
        self.topRightView.frame = rect;
 
        rect = self.bottomView.frame;
        rect.origin.y = 170;
        rect.size.width = 528;
        rect.size.height = 130;
        self.bottomView.frame = rect;
    }
    else
    {
        CGRect rect = self.topLeftView.frame;
        rect.size.width = 130;
        rect.size.height = 254;
        self.topLeftView.frame = rect;
 
        rect = self.topRightView.frame;
        rect.origin.x = 170;
        rect.size.width = 130;
        rect.size.height = 254;
        self.topRightView.frame = rect;
 
        rect = self.bottomView.frame;
        rect.origin.y = 295;
        rect.size.width = 280;
        rect.size.height = 254;
        self.bottomView.frame = rect;
    }
}

This callback occurs when the view controller is rotating to a new orientation. It looks at the orientation the view controller has rotated to and resizes the views appropriately – in this case with hardcoded offsets based on the known screen dimensions of the iPhone. This callback occurs within an animation block, so the changes in size will animate.
Don’t run the app just yet. First you have to restore the autosizing masks of all three views to the following, or the autosizing mechanism will clash with the positions and sizes you set on the views in viewWillLayoutSubviews:
That should do it. Run the app and flip to landscape. Now the views line up nicely. Flip back to portrait and verify that everything looks good there as well.
It works, but that was a lot of code you had to write for a layout that is pretty simple. Imagine the effort it takes for layouts that are truly complex, especially dynamic ones where the individual views change size, or the number of subviews isn’t fixed.
Now try running the app on the 3.5-inch simulator. Whoops. The positions and sizes of the views are wrong because the hardcoded coordinates in viewWillLayoutSubviews are based on the dimensions of the 4-inch phone (320×568 instead of 320×480). You could add another if-statement that checks the screen size and uses a different set of coordinates, but you can see that this approach is becoming unworkable quickly.

Note: Another approach you can take is to make separate nibs for the portrait and landscape orientations. When the device rotates you load the views from the other nib and swap out the existing ones. But this is still a lot of work and it adds the trouble of having to maintain two nibs instead of one. This approach is quite impractical when you’re using storyboards instead of nibs.