You are on page 1of 27

• Introduction

• A Brief History
• Objective-C
• Why Objective-C was used and why the change now
• Features of Swift
• Features taken from other languages
• Advantages of Swift
• Disadvantages of Swift
• Sample program
• References
• Swift is a programming language developed by Apple for iOS and OS X development designed to replace
Objective-C, Apple's object-oriented language. Its filename extension is .swift.

• Swift is intended to be more resilient against erroneous code and the mobile apps that will be created via swift
programming language will be much faster than the applications created via objective C.

• It uses the Objective-C runtime, allowing Objective-C, Objective-C++ and Swift code to run within a single
program so that the apps already made using Objective-C can edited using Swift.

• Swift is, in large part, a reimagining of the Objective-C language using modern concepts and syntax. Swift
took language ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
• Development on Swift began in 2010 by Chris Lattner, with the eventual collaboration of many other
programmers.

• Introduced at Apple's developer conference held in June 2014 along with a 550-page language guide in the
Apple iBooks store.

• The book “The Swift programming language” was downloaded 3,70,000 in one day from its release which is
still available for free from iBooks store.

• On June 2, 2014, the WWDC app became the first publicly released app written in Swift.
• It is a general-purpose, object-oriented programming language developed by Brad Cox and Tom Love that
adds Smalltalk-style messaging to the C programming language.

• It is the main programming language used by Apple for the OS X and iOS operating systems, and their
respective application programming interfaces (APIs), Cocoa and Cocoa Touch.

• In 1988, NeXT licensed Objective-C from Stepstone and extended its GCC compiler to support Objective-C.

• It was selected as the main language used by NeXT for its NeXTSTEP operating system, from which OS X
and iOS are derived.

• Objective-C is a thin layer on top of C, and moreover is a strict superset of C. Objective-C derives its object
syntax from Smalltalk.

• Objective-C source code program files usually have .m filename extensions, while Objective-C header files
have the same as for C header files. Objective-C++ files are denoted with a .mm file extension.
• Basic numeric types (Int, UInt, Float, Double)

• Most C operators are carried over to Swift, but there are some new operators like a…b and a..<b.

• Curly braces are used to group statements.

• Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new
identity operator, ===, is provided to check if two data elements refer to the same object.

• Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them.

• Control statements, for, while, if, switch are similar, but have extended functionality, e.g. a for in that
iterates over any collection type, a switch that takes non-integer cases, etc.
• Statements don’t need to end with a semicolon but they can be used to allow more than one statement on a line.

• Comments of the form /* ... */ can be nested, allowing blocks of code to be easily commented out.

• Functions are first-class objects & header files are not required.

• Operators can be redefined for classes (operator overloading), and new operators can be created.

• Several notoriously error-prone behaviors of C-family languages have been changed:


 No pointers exist.
 Assignments do not return a value.
 No need to use break statements in switch blocks.
 Variables and constants are always initialized and array bounds are always checked.
 Overflows, are trapped as a run-time error, but programmers can choose to allow them.
• When NeXT began, object-oriented programming hadn't been widely adopted, and few languages available
even implemented it.

• Because of the close relationship between Objective-C and the Cocoa frameworks, Objective-C enabled the
sorts of design patterns that made the frameworks effective.

• Not every developer was entirely happy with Objective-C as a language, and Apple then compounded this
problem by controlling the runtime and writing its own compiler and adding new features

• Because it was basically C with a few extensions, Objective-C was limited to using C's method of keeping
track of complex objects: pointers.

• Over time, other languages adopted some great features that were difficult to graft back onto a language like C.
• It was also possible to screw up and try to access the wrong address in memory, causing a program to crash or
opening a security hole.

• The very nature of C meant that the language would always be inherently unsafe, with stability and security
open to compromise by a single sloppy coder.

• Apple has also gained some experience with language development already, adding things like properties,
Automatic Reference Counting, and closures to Objective-C.

• Since, Apple's in control of everything, the same runtime can support both Swift and Objective-C, allowing
legacy code to be mixed in with the new language.
• Fast and Powerful
 From its earliest conception, Swift was built to be fast. Using the high-performance LLVM compiler, Swift
code is transformed into optimized native code, tuned to get the most out of modern hardware.
 The syntax and standard library have also been tuned to make the most obvious way to write your code also
perform the best.
 Swift takes the best features from the C and Objective-C languages. It includes low-level primitives such as
types, flow control, and operators.
 It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa
Touch developers the performance and power they demand.

• Modern
 Swift is the result of the latest research on programming languages, combined with decades of experience
building Apple platforms.
 Named parameters brought forward from Objective-C are expressed in a clean syntax that makes APIs in Swift
even easier to read and maintain.
 Inferred types make code cleaner and less prone to mistakes, while modules eliminate headers and provide
namespaces.
 Memory is managed automatically, and you don’t even need to type semi-colons.

• Designed for Safety


 Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers
are checked for overflow, and memory is managed automatically.
 Syntax is tuned to make it easy to define your intent — for eg., simple three-character keywords define a
variable (var) or constant (let).
 Understanding and properly handling cases where objects are nil is fundamental to the frameworks, and Swift
code makes this extremely easy.
 Adding a single character can replace what used to be an entire line of code in Objective-C.

• Interactive Playgrounds
 Playgrounds make writing Swift code incredibly simple and fun. Type a line of code and the result appears
immediately.
 If your code runs over time, for instance through a loop, you can watch its progress in the timeline assistant.
The timeline displays variables in a graph, draws each step when composing a view. When you’ve perfected
your code in the playground, simply move that code into your project.
 With playgrounds, you can design a new algorithm, watching its results every step of the way; Create new
tests, verifying they work before promoting into your test suite; Experiment with new APIs to hone your Swift
coding skills .

• Other features to make your code more expressive:


 Closures unified with function pointers
 Tuples and multiple return values
 Generics
 Structures that support methods, extensions, protocols.
• Dictionaries (aka hash tables) -- from JavaScript
 JavaScript programmers have long used square brackets to take in an integer as a traditional array or accept a
string that then behaves like a hash table.
 Now Swift programmers can do the same thing. Apple calls the hash tables "Dictionaries" and offers a clean
syntax for initializing them.

• Data structure declarations -- from C# and Java


 Java introduced Generic types in Version 5 so that programmers could tell the compiler which data type will be
pushed into the HashMaps, Arrays, or Collections.
 Around the same time, Microsoft added them to C#. Now it's Swift's turn to let programmers tell the compiler
what to expect.
• Inferred data types -- from functional programming languages
 Forcing variables to stick to a particular data type is an efficient way for programmers to catch bugs before the
code even runs. The compiler checks data types and flags incompatibilities.
 Lately some of the best compilers have started inferring types from the data, which is usually easy to do when
a variable is initialized. This began with some of the functional languages, like ML.
 Now that Microsoft added the feature to Version 3.0 of .Net, it's practically mainstream. Thanks to Swift, iOS
developers can now save a few keystrokes, too.

• Optional semicolons -- from JavaScript and Python


 Semicolon are just a simple way for designating the end of a programming statement, but somehow a growing
number of developers can't be bothered to type them.
 Semicolons are optional at the end of lines. If you want to pack multiple expressions in the same line, you'll
need a semicolon, but if you put them on individual lines, you don't need to.
• String templating -- from Cold Fusion, JSP, and others
 Many programming tools offer ways to insert a variable's value into a template. Web tools such as Cold Fusion
and Java Server Pages have long provided a simple way to mix data with HTML in templates.
 Swift offers a sleek templating system with an escaped open parentheses, followed by the expression to
evaluate, followed by a closed parentheses.

• Closures -- from Lisp and Scheme via JavaScript


 JavaScript programmers love to pack up little anonymous bits of code and pass them around like functions.
 They picked up these closures from languages like Lisp and Scheme that fully developed the idea of Lambda
functions.
 Swift now comes with closures and the ability to pass along functions as first-class objects.
• Protocols (aka interfaces) -- from Java and C#
 When programmers create elaborate object-oriented class structures in Java and C#, they often begin with an
interface at the foundation.
 The interface is a basic class that defines the structure for all of the functions that the classes must offer if they
want to fit the definition.
 Swift uses the term "protocol" for sketching out a blueprint for a collection of classes.

• Automatic reference (akin to garbage collection) -- from Java, C#, and Objective-C
 Java and C# programmers love garbage collection, at least until it causes their machine to freeze up for a
second.
 Swift uses automatic reference counting, a similar solution that's been popular with Objective-C users.
• Tuples -- from Lisp and Python
 Sometimes a method needs to return more than one value.
 Early languages like Lisp assumed that everything was a list or a tuple.
 More modern languages like Python offer explicit syntax for matching up the N value returned from a method
with the N variables that will be bound to them.
 Swift follows in this tradition.

• Signed and unsigned integers -- C# and Objective-C


 Some abstract languages, such as Java, have avoided the complexity of unsigned integers, other languages,
such as C#, have embraced them.
 Swift offers signed and unsigned integers of one, two, four, and eight bytes -- just like Objective-C.
• The bridging between Objective-C and Swift caters developers an allurement to get connected with the Xcode
tool chain.

• The apps written in Objective C requires precise testing techniques, whereas in swift programming, there is no
need for rigorous testing.

• iOS is a leading platform that offers developers with all tools as per their requirement. This helps in reducing
the risk of malicious apps, so that there won’t be any unwanted access to sensitive user data.

• The compiler is now incredibly smart about spotting common errors, and the language features several
intelligent ways to avoid doing dumb things with nil objects.

• Most of the features Swift adds already exist in other programming languages, and these will be familiar to
many developers.
• Lack of existent features in the more mature, Obj-C and dependence on pieces of Obj-C code.

• The main features present in UIKit and AppKit can only be used with Obj-C and third party libraries and
source codes are only available in Obj-C

• There are still no third parties iOS tutorials on Swift, the Objc-C community of developers is huge while
Swift’s is non-existent

• As a fast learning language, there will be an increase in competition in the App Store and developers have to
learn this language only for iOS and OS X app development.

• The goal of Swift is to reduce long, complex codes, but someone learning the language for the first time will
have to stick to long sentences and learn proper sentence structure before simplifying his/her sentences later.

• Its working is slower than Objective-C. For all the modern syntax, simplified code construction, playground
app simulation and testing, and type safety that you get, you also get somewhat slower execution speed.
You declare these as variables with a type, or you can simply assign a variable a value and Swift will
figure out which type you actually want. You can also use constants when you've got a value that's not likely to
change by using "let."

You can do this: Or, you can just do this:


var x : Int = 0 var x = 0
var y : String = “foobar” var y = “foobar”
var z : Bool = true var z = true

But, you can’t do this:


var x = 1
x = “quux” ← COMPILER ERROR

var x = 0 let y = 0
x=1 y = 1 ← COMPILER ERROR
x // x == 1
Optionals handle the absence of a value.You can unwrap the value contained in the optional by using
the bang operator. But if it’s nil, you will get a runtime error, so don’t do that.

var foo : Int? = 41


foo! == 41 // true

An another big feature is enumerators, which Apple calls "first-class types." They can have initializers
and aren't limited to associating values with integers. You only have to add an index to the first item.
enum Planet {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
enum Status {
case OnTime, Delayed(Int, String)
}
Generics are functions that can work with a variety of variable types. You can also restrict the types of
objects that a generic works on by setting them to limit their inputs to specific protocols.

Generics:- Functions:-
func swapTwoValues<T>(inout a: T, inout b: T) func swapTwoInts(inout a: Int, inout b: Int)
{ {
let temporaryA = a let temporaryA = a
a=b a=b
b = temporary b = temporaryA
} }

var designer = "Lentes"


var programmer = "Alice"
swapTwoValues(&designer, &programmer)
let newTeam = "designer is \(designer), and programmer is now \(programmer)“
// prints "designer is now Alice, and programmer is now Lentes"
Apple introduced closures, small chunks of code that can be passed around within an app. They're great
for things like dialogs, which typically have to execute some code when the user dismisses them.
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
A feature from Objective-C that's returning is the protocol, in which a class can declare itself as
guaranteeing to provide a certain amount of functionality.

protocol FullyNamed {
var fullName: String { get }
}
struct Person: FullyNamed {
var fullName: String }
let john = Person(fullName: "John Appleseed")
There's also a special type of value called a "tuple," which acts as a wrapper for multiple values. While
a function can only return one item, that item can be a tuple that wraps a combination of multiple variables of diff.
types.
var luckyNumbers: = (3, 8, 21)
luckyNumbers.2
var myDog:(Int, Int, Bool) = (age: 8, isAFemale: true)
var (age,_) = myDog

The language also includes dictionaries that can work with any of the numerical and string values,
though you can't, say, mix strings and integers in the same array.

let emptyDictionary = Dictionary<String, Float>()


var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ]
occupations.updateValue("Chief", forKey:"Malcolm")
for (name, occupation) in occupations{
println("Name: \(name) \n Occupation: \(occupation)")
}
// Swift variables are declared with "var" followed by a name, a type, and a value
var explicitDouble: Double = 70

// if the type is omitted, Swift will infer it from the variable's initial value
let implicitInteger = 70; var implicitDouble = 70.0

// define a dictionary with four items, each with a person's name and age
let people = ["Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25]

// now we use Swift's flexible enumerator system to extract both values in a single loop
for (name, age) in people { println("\(name) is \(age) years old.") }

// methods and functions are declared with the "func" syntax


func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!"
return greeting }
println(sayHello("Jane"))
• Apple’s developer website - developer.apple.com
• Wikipedia – www.wikipedia.org
• Google – www.google.com
• Quora – www.quora.com
• Arstechnica - www.arstechnica.com/apple/2014/
• Slideshare – www.slideshare.com
Seminar taken by:-
Nijo Job (54)
Semester 7 // CS-B
Seminar guide: SHEENA MATHEW

You might also like