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
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
- Download the file from http://swiftlang.org/packages/swift-0.95-RC6.tar.gz
- Extract by running “tar xfz swift-0.95-RC6.tar.gz”
- 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
NSLog(@"%@%u",user,days);
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-
print("\(user)\(days)")
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
NSDictionary
*dict = @{@
"key1"
:@
"ravi"
,@
"key2"
: @
"jaiswal"
};
// access value for key1
NSString
*value = dict[@
"key1"
];
NSLog
(@
"%@"
,value);
override func viewDidLoad() {
super.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
self.view.addSubview(scrollView)
let signupView=UIView(frame: CGRect(x: 20, y: 50, width: 330, height: 200));
signupView.layer.cornerRadius=3;
signupView.backgroundColor=UIColor.whiteColor()
self.view.addSubview(signupView)
let firstNameText = UITextField(frame: CGRectMake(30, 80, 310, 30))
firstNameText.placeholder = “Enter first name”
firstNameText.font = UIFont.systemFontOfSize(12)
firstNameText.borderStyle = UITextBorderStyle.RoundedRect
firstNameText.layer.borderColor=UIColor(red:170,
green:170,
blue:170,
alpha:1.0).CGColor
firstNameText.autocorrectionType = UITextAutocorrectionType.No
firstNameText.keyboardType = UIKeyboardType.Default
firstNameText.returnKeyType = UIReturnKeyType.Done
firstNameText.clearButtonMode = UITextFieldViewMode.WhileEditing;
firstNameText.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
self.view.addSubview(firstNameText)
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
self.view.addSubview(lastNameText)
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
self.view.addSubview(emailId)
signButton.setTitle(“Sign up”, forState: .Normal)
signButton.backgroundColor=UIColor.blueColor()
signButton.addTarget(self, action: “signUpDetail”, forControlEvents: .TouchUpInside)
self.view .addSubview(signButton)
{
var signupDictionary:NSDictionary = [“firstName”:firstNameText.text,
“lastName”:lastNameText.text,
“email”:emailId.text]
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 { print("error") return } let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) print(dataString) } task.resume() }
var horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
var verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(verticalConstraint)
var widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
view.addConstraint(widthConstraint)
var heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
view.addConstraint(heightConstraint)
We need to set apps UI in all mobile orientation mode we need to set Autolayout to all View,textfield and button etc.
References:-
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html
https://www.raywenderlich.com/115253/swift-2-tutorial-a-quick-start
https://dzone.com/articles/mobile-ui-patterns-flowchart