Why Swift?

Objective-C is a layer built on the C language, making it static, but it can also be used for dynamic typing. Apple’s Swift is a static language designed to be compatible with Objective-C, but its static-typing makes it more resilient to errors.

Swift is an alternative to the Objective-C language that employs modern programming-language theory concepts and strives to present a simpler syntax. During its introduction, it was described simply as “Objective-C without the C”

Inspired by Python, Swift aims to be easy for coding newbies to pick up, and has been designed to fix some of the issues of Objective-C.



Swift is a new programming language developed by Apple Inc.  On september 9, 2014 for iOS and OS X development. Swift 1.1 was released on October 22, 2014. Swift adopts the best of C and Objective-C, without the constraints of C compatibility.

Swift uses the same runtime as the existing Objective-C system on Mac OS and iOS, which enables Swift programs to run on many existing iOS 6 and OS X 10.8 platforms.

Swift Advantages-

  • Swift makes use of safe programming patterns.
  • Swift provides modern programming features.
  • Swift provides Objective-C like syntax.
  • Swift provides seamless access to existing Cocoa frameworks.
  • Swift unifies the procedural and object-oriented portions of the language.
  • Swift does not need a separate library import to support functionalities like input/output or string handling.
  • Performence and runtime- Swift must compile down to native code with no run time compilation or interpretation.
  • Better nil Handling.
  • Unification and Modernization of Function Types.

Swift Installation

  1. Download the file from http://swiftlang.org/packages/swift-0.95-RC6.tar.gz
  2. Extract by running “tar xfz swift-0.95-RC6.tar.gz”
  3. Add to PATH by running “export PATH=$PATH:/path/to/swift-0.95-RC6/bin”.

Difference between objective-C and Swift

  Some example in Objective -c and Swift Make Clear Difference

String Example in Objective c

In Objective-C formatting strings is usually done with the stringWithFormat: method.

NSString *user = @"Ravi";
int days = 3;
NSString *string = [NSString stringWithFormat:@"posted by %@ (%d days ago)", user, days];
print in Objective-c

String Example in Swift

Swift has a feature called string interpolation to do the same, but it is more compact and easier to read.

var user = "ravi"
var days = 3
var string = "posted by \(user) \(days) ago"
print in Swift-

Array Example in Objective-c

NSArray *array = @[@"Ravi", @"Amit", @"Sumit"];

Array in Swift

var array = ["Ravi", "Amit", "Sumit"]

Simple Function in Objective-c

function with no parameter with no return value

          – (void)signUp
Simple Function in Swift
       function with no parameter with no return value
           func gotoNext()

Dictionary Example in Objective-c
Objective-C Dictionary Object classes allow data to be stored and managed in the form of key-value pairs where both the key and the value are objects.
   NSDictionary *dict = @{@"key1":@"ravi",@"key2": @ "jaiswal"};
// access value for key1
      NSString *value = dict[@"key1"];

Dictionary Example in Swift-
      var dict=[1:”one”,2:”Two”,3:”Three”]
      var dict=dict[1]
      print(“value of key=1 is \(dict)”)

Sign up View  using Swift
 import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

//Basically Start writing code from here//
//Create ScrollView//
let  scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = UIColor.grayColor()
//        scrollView.contentSize =
scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

// create  View //
let signupView=UIView(frame: CGRect(x: 20, y: 50, width: 330, height: 200));
// Create textfield//
let firstNameText = UITextField(frame: CGRectMake(30, 80, 310, 30))
firstNameText.placeholder = “Enter first name”
firstNameText.font = UIFont.systemFontOfSize(12)
firstNameText.borderStyle = UITextBorderStyle.RoundedRect
firstNameText.autocorrectionType = UITextAutocorrectionType.No
firstNameText.keyboardType = UIKeyboardType.Default
firstNameText.returnKeyType = UIReturnKeyType.Done
firstNameText.clearButtonMode = UITextFieldViewMode.WhileEditing;
firstNameText.contentVerticalAlignment = UIControlContentVerticalAlignment.Center

let lastNameText = UITextField(frame: CGRectMake(30, 120, 310, 30))
lastNameText.placeholder = “Enter last name”
lastNameText.font = UIFont.systemFontOfSize(12)
lastNameText.borderStyle = UITextBorderStyle.RoundedRect
lastNameText.autocorrectionType = UITextAutocorrectionType.No
lastNameText.keyboardType = UIKeyboardType.Default
lastNameText.returnKeyType = UIReturnKeyType.Done
lastNameText.clearButtonMode = UITextFieldViewMode.WhileEditing;
lastNameText.contentVerticalAlignment = UIControlContentVerticalAlignment.Center

let emailId = UITextField(frame: CGRectMake(30, 160, 310, 30))
emailId.placeholder = “Enter email Id”
emailId.font = UIFont.systemFontOfSize(12)
emailId.borderStyle = UITextBorderStyle.RoundedRect
emailId.autocorrectionType = UITextAutocorrectionType.No
emailId.keyboardType = UIKeyboardType.Default
emailId.returnKeyType = UIReturnKeyType.Done
emailId.clearButtonMode = UITextFieldViewMode.WhileEditing;
emailId.contentVerticalAlignment = UIControlContentVerticalAlignment.Center


// Create button//
let signButton=UIButton(frame: CGRectMake(30, 200, 310, 30))
signButton.setTitle(“Sign up”, forState: .Normal)
signButton.addTarget(self, action: “signUpDetail”, forControlEvents: .TouchUpInside)
self.view .addSubview(signButton)
func signUpDetail()
var signupDictionary:NSDictionary = [“firstName”:firstNameText.text,
Click on Submit Button after fill all textfiled, when click on submit call   post method and send  data to server.
Post Method-
  let url:NSURL = NSURL(string: url_to_request)!
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        let paramString = "data=Hello"
        request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = session.dataTaskWithRequest(request) {
            let data, let response, let error) in
            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
Auto Layout in Swift-
Auto Layout is a system that makes it easy to support multiple screen sizes with one interface by making your interface react to changes. It does this by solving a set of layout constraints which describe the interface.
Auto Layout makes layout code much simpler to write and maintain and most of the time you don’t event have to write code. That means less time writing code and debugging it.
 Autolayout Constraints example-
    var horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)

    var verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)

    var widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)

    var heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)

We need to set apps UI in all mobile orientation mode we need to set Autolayout to all View,textfield and button etc.