SlideShare a Scribd company logo
1 of 16
Download to read offline
1Using Swift for All Apple Platforms	 Mphasis
Using Swift for All Apple Platforms
(iPhone, iPad, Apple Watch, Apple TV & Mac)
A PoV by
Aniruddha Chakrabarti
AVP Digital, Mphasis
Krishnaji Kulkarni
AVP, Mobility Practice, Mphasis
2Using Swift for All Apple Platforms	 Mphasis
Overview
Apple introduced a new language called ‘Swift’ at the 2014 Worldwide Developers Conference (WWDC). Swift is a multi-paradigm,
new generation programming language for development on all Apple platforms including iPhone (iOS), iPad (iOS), Apple Watch
(watchOS), Apple TV (tvOS) and Mac (OS X) platforms. Swift incorporates the language innovations that have happened in the
last two decades. Swift does not replace Objective-C, which was the programming language used across all the Apple platforms
including iOS, watchOS, tvOS and OS X, but it completes Objective-C and other libraries like Cocoa Touch. Swift is a compiled
programming language and belongs to the ‘C’ family of languages similar to C++, Java, C#, Objective-C and D. Swift is influenced
by dynamic programming languages like Python, Ruby and functional programming languages like Haskell.
Popularity of Swift
After Apple introduced Swift at the 2014 Worldwide Developers
Conference (WWDC), it has become widely popular within the
developers community in just a year. According to TIOBE Index,
November 2015, Swift ranks at 14th
position for being the most
popular language whereas Objective-C position has moved
down drastically from 3rd
to 15th
in a span of just one year,
clearly indicating that Swift is becoming the de-facto standard
among developers. Programming language for Apple platforms
including iPhone, iPad, Apple Watch, Apple TV and Mac (iOS,
watchOS, tvOS and OS X).
Swift has become so popular in just 18 months that it would
not be wrong to say that it’s surpassing even the uptake of Sun
Microsystems’ (now Oracle) Java programming language and
Microsoft’s C# in the late 1990s and early 2000s.
This PoV recommends the following guidelines:
•	 For Greenfield systems and apps on iOS, watchOS, tvOS and
OS X platforms, Swift should be used as the programming
language
•	 For Brownfield systems and apps (adding new features to
existing apps) on iOS, watchOS, tvOS and OS X platforms,
Swift along with Objective-C should be used as the
programming language
Note that this PoV does not cover all the features of Swift. It touches upon some
of the important and prominent features that made Swift popular.
iPhone
(iOS)
Apple Watch
(watchOS)
iPad
(iOS)
Apple TV
(tvOS)
Mac
(OS X)
Swift gained huge
popularity among the
developer communities
within a year of its launch.
Figure: TIOBE Language Index listing programming languages by popularity (December 2015)
Dec 2015 Dec 2014 Change Programming Language Rating Change
1 2 Java 20.973% +6.01%
2 1 C 16.460% -1.13%
3 4 C++ 5.943% -0.16%
4 8 Python 4.429% +2.14%
5 5 C# 4.114% -0.21%
6 6 PHP 2.792% +0.05%
7 9 Visual Basic .NET 2.390% +0.16%
8 7 JavaScript 2.363% -0.07%
9 10 Perl 2.209% +0.38%
10 18 Ruby 2.061% +1.08%
11 32 Assembly Language 1.926% +1.40%
12 11 Visual Basic 1.654% -0.15%
13 16 Delphi/Object Pascal 1.405% +0.52%
14 17 Swift 1.405% +0.34%
15 3 Objective-c 1.357% -7.77%
3Using Swift for All Apple Platforms	 Mphasis
Figure: TIOBE Language Index showing rise in the popularity of Swift language
Historically, developers have used Objective-C for developing
apps for iOS and OS X platforms. Objective-C, which is a
superset of C with object-oriented constructs, was originally
created by NeXT for its NeXTSTEP operating system in the 1980s.
It lacks many of the new language design features invented and
made popular in last three decades. Swift is Apple’s attempt to
create a new, modern language for iOS, OS X, watchOS and
new tvOS platforms.
Swift Version 2 was released in WWDC 2015.
Swift uses LLVM compiler infrastructure, which is a set of library
files, re-usable low level tools and components for compilers.
Languages that use LLVM includes Objective-C, Python, D,
Scala, Ruby, R, Rust, Go and many more. LLVM infrastructure
is also used for clang compiler - a new compiler for C, C++ and
Objective-C.
LLVM Project is jointly designed and developed by Vikram Adve
and Chris Lattner. Currently, Chris Lattner works at Apple Inc. as
the chief designer for Swift language.
In 2012, both of them were awarded with the prestigious ACM
Software System Award for breakthrough innovation and lasting
influence in LLVM.
In December 2015, Apple decided to make Swift as an open
source platform by releasing the source code and library
files to GitHub. Implementation of Swift on Linux (Ubuntu) is
currently available at swift.org community site. Following Apple’s
announcement, IBM ported Swift to Linux and introduced IBM
Swift Sandbox, which is an online REPL (Read-eval-print loop) for
executing small Swift code snippets. The Swift code, written in
the online REPL, is executed on the Linux backend server and the
results are then displayed in the web console.
Advantages of Swift over Objective-C
•	 Swift is designed with a philosophy ‘Simplicity is the Ultimate
Sophistication’, so programs written in Swift are quite easier
to read, write and maintain while compared to Objective-C
programs
•	 It’s built from ground up hence Swift incorporates the
best-of-breed language design
•	 Swift is much safer and faster than Objective-C
•	 Swift supports Automatic Memory Management feature
•	 As Swift requires less effort for coding/programming due to
its low learning curve, it helps in yielding a good productivity
graph at a faster rate
•	 Swift has a low entry barrier and is easier to learn than
Objective-C. Programmers, with background in other modern
programming languages like Python, Ruby, C#, Java or Scala,
easily learn Swift as they find many similar concepts.
•	 Swift has better syntax when compared to Objective-C
(though syntax is more of a personal preference, most of
the programmers like Swift’s syntax more than Objective-C’s
syntax).
TIOBE Index for Swift
Source: www.tiobe.com
1.75
1.5
1.25
1
0.75
.5
0.25
0
Jul' 14 Oct' 14
Ratings(%)
Jan' 15 Apr' 15 Jul' 15 Oct' 15
In December 2015,
Apple decided to open source Swift.
Swift source code and libraries were
released to GitHub. Implementation
of Swift on Linux (Ubuntu) is
currently available at swift.org
community site.
4Using Swift for All Apple Platforms	 Mphasis
In Swift, var keyword is used to declare a variable which is mutable and whose value can change throughout the life of the program
var age = 30
age = 35
In Swift, let keyword is used to declare immutable values (or constants)
let PI = 3.14
// Swift would not allow the below line and would give compile time error
PI = 3.14159
2. Type Inference
Swift tries to infer the type of a variable when you initialize it. Variables are declared using the var keyword and constants, using the let
keyword.
var lang = "Swift"		 // lang is inferred as String
Though types are inferred, it’s also possible to annotate a variable with type information
var lang: String = "Swift"	 // lang is explicitly declared as String
If the declaration is missing initialization, then type information has to be supplied mandatorily
var lang: String
var lang		 // this statement is illegal and generates compiler error
Swift can infer types for all types including String, Int, Double, Boolean etc.
var org = "Mphasis"	 // org is inferred as String
var age = 35		 // age is inferred as Int
let PI = 3.14159		 // PI is inferred as Double
let isFTE = true		 // isFTE is inferred as Boolean
Type inference reduces the amount of code developers have to write. Though Swift uses Type Inference, it’s a statically, and not dynamically,
typed language. So type inferred could not be changed later.
var age = 35		 // age is inferred as Int
age = "Twenty"		 // Generates a compile time error
Swift is a type-safe language - it performs type checks when the code flags any mismatched types as errors.
3. String Interpolation
String Interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result that has the placeholders
replaced by their corresponding values.
var firstName = "Steve"
var lastName = "Jobs"
var age = 50
Salient Language Features of Swift
1. Immutability
Though imperative programming languages support the concept of
immutability (through constants), Functional Programming Languages suggest
the use of immutability in many situations. Immutability comes as a great tool in
parallel processing scenarios, as mutability is difficult to handle when multiple
threads are trying to change the value of a variable.
Type Inference
Automatic
Memory
Management
Generics
Optional
Closures
First Class
Functions
5Using Swift for All Apple Platforms	 Mphasis
// String interpolation is used to embed variables within string literal
print("My name is (firstName) (lastName) and I am (age) years old")
// prints My name is Steve Jobs and I am 50 years old
// Without string interpolation – prints the same output
print("My name is " + firstName + " " + lastName + " and I am " + String(age) + "
years old")
4. First Class Functions
Swift supports First Class functions, which is a core tenant of Functional Programming. Functions are treated as first class objects. Functions
could be assigned to a variable; declared as nested function; and can accept and return other functions.
Nested Functions
func complexCalc(a: Int, b:Int) -> Int {
	 // square is a nested function declared within the parent function body
	 func square(x: Int) -> Int{			
		 return x * x
	}
	 // Nested function declared before is invoked
return square(a) + square(b)
}
print(complexCalc(10, b:20))		 // prints 500
Functions can return another function
func retFunc() -> (Int, Int) -> Int {
	 func add(num1: Int, num2: Int) -> Int {
		 return num1 + num2
	}
return add			 // retFunc returns add function
}
var delegate = retFunc()
print(delegate(20, 30))		 // prints 50
Functions can accept another function as parameter. This allows the function’s caller to provide some aspects of a function’s implementation
when the function is called – this is very similar to Strategy or Template Method design pattern. This is very helpful for API developers. In the
below example acceptFunc accepts a function that provides the calculation logic.
func acceptFunc(calcFunction:(Int, Int) -> Int, a:Int, b:Int) {
		 print("Result: (calcFunction(a, b))")
}
var addFunction = { (x:Int, y:Int) -> Int in
		 return x + y
}
var mulFunction = { (x:Int, y:Int) -> Int in
		 return x * y
}
acceptFunc(addFunction, a:10, b:20)			 // prints Result: 30
acceptFunc(mulFunction, a:10, b:20)			 // prints Result: 200
5. Internal and External Names of Function Parameters
Just like Objective-C, Swift supports internal and external names for function parameters. A function parameter in Swift can have
two names – an internal name, used within the function body to refer the parameter, and an external name of the parameter, used by the
caller while calling the function.
6Using Swift for All Apple Platforms	 Mphasis
In the below example add function accepts two Int parameters – the first parameter has an internal name of x, and the external name is
num1. The second parameter has an internal name y, and the external name is num1.
// add function declares different external and internal names for parameters
// for the first parameter the internal name is x, while the external name is num1
// for second parameter the internal name is y, while the external name is num2
// internal parameter names are used within the function body
// while external parameter names are used when invoking the function
func add(num1 x:Int, num2 y:Int) -> Int {
	 return x+y
}
print(add(num1: 20, num2: 10))	 // prints 30
To keep the external parameter name same as internal _ could be mentioned as external parameter name. So in the below example
the internal as well as external parameter names are same and function calls could be made without specifying the named parameter.
func add(_ x:Int, _ y:Int) -> Int {
	 return x+y
}
print(add(20, 10))		 // prints 30
6. Enumerations
Enumerations or ‘enums’ group related values and allows to work with these in a type safe way. Typically in languages that do not support
enumerations, constants are used for this purpose but enums are type safe and improve the readability of the code.
Below code example declares an enumeration called Animal that has three values Dog, Cat and Cow
enum Animals {
	 case Dog
	 case Cat
	 case Cow
}
let dog = Animals.Dog
print(dog)
let tiger = Animals.Tiger		 // compile time error since Tiger is not a member
The values of the enum could be declared in the same line, separated by comma –
enum Animals {
case Dog, Cat, Cow
}
Individual enumeration values could be checked using a switch statement also -
enum Animals {
	 case Dog, Cat, Cow
}
var animal = Animals.Cow
switch animal {
	 case .Dog:
print("The animal is Dog")
	 case .Cat:
print("The animal is Cat")
	case .Cow:
print("The animal is Cow")
}
7Using Swift for All Apple Platforms	 Mphasis
7. Tuples
Tuples allow grouping multiple values into a single compound value. For example, employee name and age could be grouped together as a
tuple. Tuples can contain any data types and any number of values, although typically it’s used for a pair of values.
Below a tuple, called employee is declared with two elements – a String and an Integer. It’s called a Tuple with type (String, Int)
var employee = ("Bill", 35)		 // employee is a tuple with two elements
Individual elements of a tuple could be accessed as tuple.index numbers with index starting at 0
print(employee.0)				 // prints Bill
print(employee.1)				 // prints 35
Individual elements of a tuple could be named while declaring it, though it’s optional. Typically, in functional programming languages, tuple
elements are not named to keep the syntax minimal.
var employee = (name: "Bill", age: 35)		
// first element of the tuple is name and second element is age
If individual elements are named then they could be accessed using the tuple.element syntax
print(employee.name)			 // prints Bill
print(employee.age)			 // prints 35
Tuples could have more than two elements
var employee = ("Bill", 35, 1234.55, true)
print(employee.2)
print(employee.3)
One interesting use case of Tuple is, it allows to return multiple values from a function.
func addAndSubtract(num1: Int, num2: Int) -> (Int,Int) {
	 return (num1 + num2, num1 - num2)
}
print(addAndSubtract(20, num2:10))		 // prints (30, 10)
Tuple’s elements could be decomposed using multiple variable declaration
func addAndSubtract(num1: Int, num2: Int) -> (Int,Int) {
	 return (num1 + num2, num1 - num2)
}
let resTuple = addAndSubtract(20, num2:10)
let (addRes, subRes) = resTuple	
// decompose tuples elements into individual variables
print(addRes)				 // prints 30
print(subRes)				 // prints 10
8. Type Aliases
Type aliases allows to define an alternative name for an existing type. Later, new variables are eligible to use a new alternative name.
// declare a Type alias alternate type EmployeeId for UInt16
typealias EmployeeId = UInt16
// While declaring the variable use the Type alias alternate type
var id: EmployeeId
id = 2
print(id)			 // prints 2
Type aliases could be used for complex types as Tuple also
// declare a Type alias for a Tuple of type String, Int to hold name and age
typealias Employee = (String, Int)
8Using Swift for All Apple Platforms	 Mphasis
// While declaring the variable use the Type alias alternate type
var emp: Employee
emp = ("John", 55)
print(emp.0)		 // prints John
print(emp.1)		 // prints 55
9. Optional Type and Optional Chaining
Swift supports Optional Types that handles the absence of a value. Using optionals is similar to using nil with pointers in Objective-C,
but they work for any type, not just classes. The options help avoid unnecessary nil checks before accessing the objects.
So value of an Optional type would either be some value or nil. Optional types are declared by marking ? after type name.
var age: Int?	 // age is declared as Int? or optional int
print(age)		 // since it’s not initialized to any value, it’s value is nil
age = 10
print(age)		 // prints 10, since it’s initialized to value 10
The optional type wraps the variable and to access these objects, operator ‘!’ used to forced unwrapping & getting the underneath value.
This can also be achieved by using implicit wrapping, while defining, as below.
var name: String!	 // Name is implicit unwrapping of the optional name variable
print(“Name is (name)”)	
// since it’s not initialized to any value, it’s value is nil
name = "Anamika"
print("Name is (name)")		 // prints “Name is Anamika” since initialized
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.
class Employee{
	 var firstName: String = ""
	 var lastName: String?		 // lastName property is optional
	 var designation: String = ""
	 var address: Address?		 // Optional chaining – Address is optional
init(firstName: String, designation: String, address: Address?){
		 self.firstName = firstName
		 self.designation = designation
		 self.address = address
	}
}
class Address{
	 var streetAddress: String?	 // streetAddress property is optional
	 var city: String = ""
	 var country: String = ""
	 init(city: String, country: String){
self.city = city
self.country = countr
	}
}
var add = Address(city: "Mpls", country: "USA")
var emp = Employee(firstName: "John", designation: "Architect", address: add)
print("Name - (emp.firstName) (emp.lastName)")
// prints Name - John nil as lastName property is nill
print("Address - (emp.address!.streetAddress) (emp.address!.city)
	 (emp.address!.country)")
// prints Address - nil Mpls USA as Address.streetAddress property is nill
9Using Swift for All Apple Platforms	 Mphasis
10. Closures
Closures are anonymous functions or self-contained blocks of functionality. Closures could be returned or passed as parameters to named
functions. They could be assigned to variables. Closures in Swift are similar to blocks in C and Objective-C, and to lambdas or anonymous
functions in other programming languages like C# and Java.
Below is an example of closure or anonymous function. Here the closure is assigned to the variable add -
let add = { (x:Int, y:Int) -> Int in
	 return x + y
}
print(add(20,10)) 		 // prints 30
This could be further simplified by taking advantage of type inference. In the below example types of x and y parameters are inferred -
let add = { x, y -> Int in
	 x + y		 // same as return x+y, return is optional for last statement
}
print(add(20,10)) 		 // prints 30
The function body could be further simplified by writing in the same line –
let add = { x, y -> Int in x + y }
print(add(20,10))		 // prints 30
Collection class functions like sort, filter and map accept closure as parameters. Following code snippet uses sort function that accepts a
closure to sort an array -
let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"]
var sortedCities = cities.sort( { (s1:String, s2:String) -> Bool in return s1 < s2
})
print(sortedCities)
// prints ["Bangalore", "Chennai", "Delhi", "Kolkata", "Mumbai"]
Following code snippet uses filter function that accepts a closure to filter cities that start with “B” -
let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"]
var filteredCities = cities.filter({(str:String) -> Bool in return str.hasPrefix("B")})
print(filteredCities)
// prints ["Bangalore"]
Swift automatically provides shorthand names for arguments to inline closures - $0, $1, $2 ... $n etc. These refer to the values of the
closure’s arguments and need not be declared explicitly, so the sort could be simplified as –
let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"]
var sortedCities2 = cities.sort( { $0 < $1 } )
print(sortedCities2)
// prints ["Bangalore", "Chennai", "Delhi", "Kolkata", "Mumbai"]
11. Properties
Properties are class level instance variables on steroid. In languages, that do not support Properties, instance variables are made private
(or protected) so that clients outside the class cannot assign invalid value to the instance variable. For setting and getting values of class
members, setter and getter methods are used. Properties support this principle formally through language. Other programming languages,
like C#, also support properties as language feature.
In the below example Age is the property of class Employee, the type of Age is Int. The property has both a getter and a setter -
class Employee {
private var _age : Int = 0
10Using Swift for All Apple Platforms	 Mphasis
var Age: Int {
get {
return _age
}
set {
if newValue < 0 {
print("Age cannot be negative")
}
else{
_age = newValue
}
}
}
}
var emp = Employee()
emp.Age = -10			 // prints Age cannot be negative
emp.Age = 30
print(emp.Age)			 // prints 30
12. Subscripts
Subscripts are widely used to access elements of a collection type like Array, sets and dictionary using the familiar collection[index] syntax.
Subscripts provide shorthand for getting and setting values of the elements of a collection.
In the below example, a class called Employees is defined, which can hold name of multiple employees. Employees class allows getting and
setting employee names for a specific index using Subscripts. Subscript syntax is similar to property syntax – The subscript can have both
a getter and a setter.
class Employees {
	 var _emps = [String]()
	func add(name: String) {
		 _emps.append(name)
	}
	 var count: Int {
		 get {
			 return _emps.count
		}
	}
subscript(index: Int) -> String {
	 get{
		 return _emps[index]
		}
		 set(newValue) {
			 _emps[index] = newValue
}
}
}
var employees = Employees()
employees.add("Aniruddha")
employees.add("Bill")
employees.add("Krishna")
11Using Swift for All Apple Platforms	 Mphasis
print(employees.count)			 // prints 3
print(employees[1])			 // prints Bill. Gets the employee at index 1
employees[1] = "Steve"			 // Sets the employee an index 1
print(employees[1])			 // prints Steve. Gets the employee at index 1
13. Operator Overloading
Operator overloading is a key feature provided by most of the Object Oriented languages, including C++. Swift supports operator
overloading, which allows to change or redefine existing operators’ work for classes or structures. For example, Swift’s built-in String class
does not provide an implementation of multiplication (*) operator. So the below code generates a compile time error –
print("Aniruddha" * 4)		 // compile tile error
But it’s possible to provide implementation of multiplication operator of built-in String class so that it adds the string value to number of
times. So “a” * 5 would result in “aaaaa” -
// * or multiply operator overloaded for String
// This would be invoked when the sequence is String * Int
func * (value: String, no: Int) -> String {
		 var result = ""
		 for var ctr = 0; ctr < no ; ++ctr {
			 result += value
		}
		 return result
}
print("Aniruddha" * 4)		 // prints AniruddhaAniruddhaAniruddhaAniruddha
14. Extension
Extension is a unique feature of Swift, which adds new functionality to an existing class, structure, enumeration, or protocol type.
Using Extension, even classes for which source code is not available could be extended – examples are library classes or built in
classes like String or Int.
Objective-C has a similar feature called categories, but other C family languages do not support the same. Extension is a very powerful
mechanism and directly supports Open Closed Principle (OCP) of SOLID object oriented principles.
import Foundation
// Built in String class is extended and a toUpper() method is added
extension String{
func toUpper() -> String {
return self.uppercaseString
}
}
// Built in String class is extended and a toLower() method is added
extension String{
func toLower() -> String {
return self.lowercaseString
}
}
var city = "Bangalore"
// Added extended methods on String are invoked
print(city.toUpper())		 // prints BANGALORE
print(city.toLower())		 // prints bangalore
12Using Swift for All Apple Platforms	 Mphasis
15. Protocols
Protocols are equivalent of Interface or Contracts in other programming language. A Protocol defines the signatures of methods, properties,
and other requirements for a class, structure or enumeration. Protocols do not contain the implementation - class, structure or enumerations
adopt the protocol and provide the implementation of the contract or blueprint defined in the protocol.
In the below example, class Bird adopts or implements both Flyable and Runnable protocols whereas class Human adopts only Runnable
protocol -
protocol Flyable{
func fly()
}
protocol Runnable{
func run()
}
// class Bird is adopting Flyable and Runnable protocols
class Bird : Flyable, Runnable{
func fly(){
print("I can fly")
}
func run(){
print("I can run too")
}
}
// class Human is adopting Runnable protocol
class Human : Runnable{
func run(){
print("I can run")
}
}
var bird = Bird()
var human = Human()
bird.fly()			 // prints “I can fly”
bird.run()			 // prints “I can run too”
human.run()			 // prints “I can run only”
Protocols can specify methods, properties, initializers (also called constructor in other languages) etc in the definition.
16. Generics
// Declare a generic function that accepts parameters of any type, swaps them
// and returns the swapped value as Tuple.
func swap<T>(arg1: T, arg2: T) -> (T, T) {
return (arg2, arg1)
}
var resInt = swap(10, arg2:20)
print(resInt)				 // prints (20, 10)
var resDbl = swap(100.50, arg2:576.6789)
print(resDbl)				 // prints (576.6789, 100.50)
var resStr = swap("Hello", arg2:"World")
print(resStr)				 // prints ("World", "Hello")
13Using Swift for All Apple Platforms	 Mphasis
17. Swift Standard Library
Swift Standard Library defines a base layer of functionality for writing
Swift programs – it contains fundamental data types, common
data structures, base protocols, commonly used function etc. It is
similar to .NET BCL (Base Class Library) or Java Class Library which
abstracts and contains similar features. The Swift Standard Library
consists of –
•	Basic data types like Int, String and Double
•	Common data structures such as Array, Dictionary and Set
•	Common functions and methods like print
•	Protocols that describe abstractions such as Comparable (used
for comparing types), Equatable (base protocol for comparing
for value equality using operators == and !=) and Streamable
(base protocol for providing text streaming functionality) as well
as other standard base protocols
Other differences between Swift and Objective-C
•	Typically in C family languages, including Objective-C,
statements need to end with ‘;’. In Swift, statements need not
have ‘;’ at the end (similar to JavaScript)
•	Header files are not required in Swift
•	Swift supports new features like type inference, generics,
first class functions, tuples etc., which are not present in
Objective-C
•	Pointers are not exposed by default in Swift while Objective-C
supports pointers
•	Strings in Swift fully support Unicode. Even variable names
support Unicode
•	Swift supports operator overloading
•	String handling is much easier and elegant in Swift in
comparison to Objective-C
Conclusion
Swift has attained great popularity among developers community
in just one year. It is a modern, fast and fun-to-learn programming
language, designed for mobile and cloud scenarios. There
are many advantages of using Swift over Objective-C. For all
Greenfield apps, Swift is fast becoming the de-facto standard for
all Apple platforms including iOS, watchOS, tvOS and OS X. We
envision that Swift would play a huge role in future Apple projects
like VR headset, Connected Car, and health band. We believe Swift
would play a dominant role in not only Apple platforms, but could
also become a significant programming language across varied
platforms.
After Apple open sourced Swift, there has been wide interest in
implementing Swift in other platforms, like Linux as well as in other
non-Apple platforms. We also see a community being built up
around Swift.
Swift Standard Library
defines a base layer of
functionality for writing
Swift programs – it contains
fundamental data types,
common data structures, base
protocols, and commonly used
function, etc.
For all Greenfield apps,
Swift is fast becoming the
de-facto standard for all
Apple platforms including iOS,
watchOS, tvOS and OS X.
14Using Swift for All Apple Platforms	 Mphasis
References
Overview of Swift (Wikipedia) - https://en.wikipedia.org/wiki/Swift_(programming_language)
LLVM - https://en.wikipedia.org/wiki/LLVM
Swift Language Guide - https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
TheBasics.html
Swift Standard Library - https://developer.apple.com/library/ios//documentation/General/Reference/SwiftStandardLibraryReference/index.html
Open Source Swift Community – http://swift.org
Public source code of Swift - https://github.com/apple
IBM Swift Sandbox / REPL - http://swiftlang.ng.bluemix.net/#/repl
Swift 3.0 and future enhancements - https://github.com/apple/swift-evolution
Copyright ©: The brand names mentioned in this PoV (Apple, Swift, iOS, OS X, iPhone, iPad, Apple Watch, Apple TV, Mac, Objective-C, etc.) belong to their
respective owners.
15Using Swift for All Apple Platforms	 Mphasis
Aniruddha Chakrabarti
Associate Vice President, Digital, Mphasis
Aniruddha possess 16 years of IT experience spread across systems
integration, technology consulting, IT outsourcing, and product development.
He has extensive experience of delivery leadership, solution architecture,
pre-sales, technology architecture, and program management of large scale
distributed systems.
As AVP, Digital in Mphasis Aniruddha is responsible for Presales, Solution, RFP/
RFI and Capability Development of Digital Practice. Prior to joining Mphasis
he has played various leadership and architecture focused roles in Accenture,
Microsoft, Target, Misys and Cognizant. He has been Lead Architect for many
large scale distributed systems. His interests include digital, cloud, mobility, IoT,
distributed systems, web, open source, .NET, Java, programming languages
and NoSQL. His industrial experience spans across different verticals such as:
Retail, Healthcare, Capital Markets, Insurance, Travel, Hospitality, Pharma and
Medical Technology.
Krishnaji Kulkarni
Associate Vice President, Mobility Practice, Mphasis
Krishnaji Kulkarni has 20+ years of IT experience, having involved in
architectural and delivery solutions for large scale projects/programs
across industry verticals. His experience spreads across mobility, Systems
Integration (SI), business process automation and web technologies.
As AVP & Lead - Mobility Practice in Mphasis, he is responsible for pre-sales,
RFP/RFI solution architecting, practice capability building and the SME support
to the delivery teams. In the last couple of years, he had closely worked with
leadership of key accounts to nurture digital transformation opportunities and
played an instrumental role in building into successful long-term relationships.
16Using Swift for All Apple Platforms	 Mphasis
VAS21/03/16USLETTERBASIL3849
For more information, contact: marketinginfo@mphasis.com
USA
460 Park Avenue South
Suite #1101
New York, NY 10016, USA
Tel.: +1 212 686 6655
Fax: +1 212 683 1690
Copyright © Mphasis Corporation. All rights reserved.
UK
88 Wood Street
London EC2V 7RS, UK
Tel.: +44 20 8528 1000
Fax: +44 20 8528 1001
INDIA
Bagmane World Technology Center
Marathahalli Ring Road
DoddanakundhiVillage,Mahadevapura
Bangalore 560 048, India
Tel.: +91 80 3352 5000
Fax: +91 80 6695 9942
About Mphasis
Mphasis is a global Technology Services and Solutions company specializing in the areas of Digital and Governance, Risk & Compliance. Our solution
focus and superior human capital propels our partnership with large enterprise customers in their Digital Transformation journeys and with global
financial institutions in the conception and execution of their Governance, Risk and Compliance Strategies. We focus on next generation technologies for
differentiated solutions delivering optimized operations for clients.
www.mphasis.com

More Related Content

What's hot

PHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonPHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonHaim Michael
 
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?NIIT India
 
Programming languages
Programming languagesProgramming languages
Programming languagesSimon Mui
 
Swift vs flutter pixel values technolabs
Swift vs flutter pixel values technolabsSwift vs flutter pixel values technolabs
Swift vs flutter pixel values technolabsPixel Values Technolabs
 
Handout 00 0
Handout 00 0Handout 00 0
Handout 00 0Mahmoud
 
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
Hack in the Box GSEC 2016 - Reverse Engineering Swift ApplicationsHack in the Box GSEC 2016 - Reverse Engineering Swift Applications
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applicationseightbit
 
Swift should I switch?
Swift should I switch?Swift should I switch?
Swift should I switch?wulfgeng
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone DevelopmentThoughtWorks
 
The Ring programming language version 1.10 book - Part 6 of 212
The Ring programming language version 1.10 book - Part 6 of 212The Ring programming language version 1.10 book - Part 6 of 212
The Ring programming language version 1.10 book - Part 6 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202Mahmoud Samir Fayed
 
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...EnlightenmentProject
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof languagenicky_walters
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overviewagorolabs
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#rahulsahay19
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
The Ring programming language version 1.3 book - Part 4 of 88
The Ring programming language version 1.3 book - Part 4 of 88The Ring programming language version 1.3 book - Part 4 of 88
The Ring programming language version 1.3 book - Part 4 of 88Mahmoud Samir Fayed
 

What's hot (20)

Java vs python
Java vs pythonJava vs python
Java vs python
 
PHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonPHP, Java EE & .NET Comparison
PHP, Java EE & .NET Comparison
 
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
Swift vs flutter pixel values technolabs
Swift vs flutter pixel values technolabsSwift vs flutter pixel values technolabs
Swift vs flutter pixel values technolabs
 
Handout 00 0
Handout 00 0Handout 00 0
Handout 00 0
 
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
Hack in the Box GSEC 2016 - Reverse Engineering Swift ApplicationsHack in the Box GSEC 2016 - Reverse Engineering Swift Applications
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
 
Swift should I switch?
Swift should I switch?Swift should I switch?
Swift should I switch?
 
ASSIGNMENT-II(a)
ASSIGNMENT-II(a)ASSIGNMENT-II(a)
ASSIGNMENT-II(a)
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone Development
 
The Ring programming language version 1.10 book - Part 6 of 212
The Ring programming language version 1.10 book - Part 6 of 212The Ring programming language version 1.10 book - Part 6 of 212
The Ring programming language version 1.10 book - Part 6 of 212
 
An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...
 
The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202
 
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...
[E-Dev-Day-US-2015][9/9] High Level Application Development with Elua (Daniel...
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
Ndu06 typesof language
Ndu06 typesof languageNdu06 typesof language
Ndu06 typesof language
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overview
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
The Ring programming language version 1.3 book - Part 4 of 88
The Ring programming language version 1.3 book - Part 4 of 88The Ring programming language version 1.3 book - Part 4 of 88
The Ring programming language version 1.3 book - Part 4 of 88
 

Viewers also liked

Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Aniruddha Chakrabarti
 
Mphasis bangalore march
Mphasis bangalore marchMphasis bangalore march
Mphasis bangalore marchPratik Jadhav
 
Kalender 2015 zum ausdrucken - kartenbauer.ch
Kalender 2015 zum ausdrucken - kartenbauer.chKalender 2015 zum ausdrucken - kartenbauer.ch
Kalender 2015 zum ausdrucken - kartenbauer.chwww.kartenbauer.ch
 
Ud1 actividad evaluable frederic martín
Ud1 actividad evaluable frederic martínUd1 actividad evaluable frederic martín
Ud1 actividad evaluable frederic martínFredi Martin
 
Dereitos Humanos
Dereitos HumanosDereitos Humanos
Dereitos Humanosguest2fe2b5
 
Conversacion entre gallegos y americanos.
Conversacion entre gallegos y americanos.Conversacion entre gallegos y americanos.
Conversacion entre gallegos y americanos.xandecarud
 
Prevention of hybrid mismatches as a justification
Prevention of hybrid mismatches as a justificationPrevention of hybrid mismatches as a justification
Prevention of hybrid mismatches as a justificationRamon Tomazela
 
Sitios Turísticos de Puerto Colombia
Sitios Turísticos de Puerto ColombiaSitios Turísticos de Puerto Colombia
Sitios Turísticos de Puerto Colombiadageratencia10a
 
Un pò della nostra vita
Un pò della nostra vitaUn pò della nostra vita
Un pò della nostra vitaNívia
 
Inscripcion asociados ascreme
Inscripcion asociados ascremeInscripcion asociados ascreme
Inscripcion asociados ascremeDiseny Jaro
 

Viewers also liked (20)

Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
 
Mphasis bangalore march
Mphasis bangalore marchMphasis bangalore march
Mphasis bangalore march
 
Kalender 2015 zum ausdrucken - kartenbauer.ch
Kalender 2015 zum ausdrucken - kartenbauer.chKalender 2015 zum ausdrucken - kartenbauer.ch
Kalender 2015 zum ausdrucken - kartenbauer.ch
 
Presentación Grupo 09
Presentación Grupo 09Presentación Grupo 09
Presentación Grupo 09
 
Dot Cvfmggdeltron 2009.Doc
Dot Cvfmggdeltron 2009.DocDot Cvfmggdeltron 2009.Doc
Dot Cvfmggdeltron 2009.Doc
 
Bonos de regalo 91 278 03 91
Bonos de regalo 91 278 03 91Bonos de regalo 91 278 03 91
Bonos de regalo 91 278 03 91
 
Sauerland Urlaub
Sauerland UrlaubSauerland Urlaub
Sauerland Urlaub
 
Resultats
ResultatsResultats
Resultats
 
Cornelia Funke
Cornelia FunkeCornelia Funke
Cornelia Funke
 
Ud1 actividad evaluable frederic martín
Ud1 actividad evaluable frederic martínUd1 actividad evaluable frederic martín
Ud1 actividad evaluable frederic martín
 
Dereitos Humanos
Dereitos HumanosDereitos Humanos
Dereitos Humanos
 
Conversacion entre gallegos y americanos.
Conversacion entre gallegos y americanos.Conversacion entre gallegos y americanos.
Conversacion entre gallegos y americanos.
 
2012_Fall_ISSUU
2012_Fall_ISSUU2012_Fall_ISSUU
2012_Fall_ISSUU
 
English for life
English for lifeEnglish for life
English for life
 
Prevention of hybrid mismatches as a justification
Prevention of hybrid mismatches as a justificationPrevention of hybrid mismatches as a justification
Prevention of hybrid mismatches as a justification
 
Sitios Turísticos de Puerto Colombia
Sitios Turísticos de Puerto ColombiaSitios Turísticos de Puerto Colombia
Sitios Turísticos de Puerto Colombia
 
Arabedes
ArabedesArabedes
Arabedes
 
Un pò della nostra vita
Un pò della nostra vitaUn pò della nostra vita
Un pò della nostra vita
 
Inscripcion asociados ascreme
Inscripcion asociados ascremeInscripcion asociados ascreme
Inscripcion asociados ascreme
 
caraculo
caraculocaraculo
caraculo
 

Similar to Swift Apple Platforms

Swift-Changing the Face of App Development.pdf
Swift-Changing the Face of App Development.pdfSwift-Changing the Face of App Development.pdf
Swift-Changing the Face of App Development.pdfTechugo Canada
 
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptx
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptxSwift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptx
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptxSample Assignment
 
What is Swift? Features, advantages, and syntax basics
What is Swift? Features, advantages, and syntax basicsWhat is Swift? Features, advantages, and syntax basics
What is Swift? Features, advantages, and syntax basicsSample Assignment
 
Which programming language should you learn next?
Which programming language should you learn next? Which programming language should you learn next?
Which programming language should you learn next? Ganesh Samarthyam
 
10 reasons why swift is best for i os app development
10 reasons why swift is best for i os app development10 reasons why swift is best for i os app development
10 reasons why swift is best for i os app developmentMoon Technolabs Pvt. Ltd.
 
Swift App Development Company.pdf
Swift App Development Company.pdfSwift App Development Company.pdf
Swift App Development Company.pdfTechugo
 
Reasons to Choose Swift for iOS App Development.pdf
Reasons to Choose Swift for iOS App Development.pdfReasons to Choose Swift for iOS App Development.pdf
Reasons to Choose Swift for iOS App Development.pdfFuGenx Technologies
 
Computer languages
Computer languagesComputer languages
Computer languageswow_so
 
Unit 4 Assignment 1 Comparative Study Of Programming...
Unit 4 Assignment 1 Comparative Study Of Programming...Unit 4 Assignment 1 Comparative Study Of Programming...
Unit 4 Assignment 1 Comparative Study Of Programming...Carmen Sanborn
 
Hire expert swift developer
Hire expert swift developerHire expert swift developer
Hire expert swift developerAxis Technolabs
 
Different Programming Languages Analysed.pdf
Different Programming Languages Analysed.pdfDifferent Programming Languages Analysed.pdf
Different Programming Languages Analysed.pdfSeasia Infotech
 
The different kind of programming language
The  different kind of programming languageThe  different kind of programming language
The different kind of programming languageMd Amran
 
Evolution Of Object Oriented Technology
Evolution Of Object Oriented TechnologyEvolution Of Object Oriented Technology
Evolution Of Object Oriented TechnologySharon Roberts
 
Top iOS App Development Tools That You Can Consider.pdf
Top iOS App Development Tools That You Can Consider.pdfTop iOS App Development Tools That You Can Consider.pdf
Top iOS App Development Tools That You Can Consider.pdfHarryParker32
 
What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...BlockchainX
 

Similar to Swift Apple Platforms (20)

Swift-Changing the Face of App Development.pdf
Swift-Changing the Face of App Development.pdfSwift-Changing the Face of App Development.pdf
Swift-Changing the Face of App Development.pdf
 
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptx
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptxSwift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptx
Swift The Complete Guide for Beginners, Intermediate, and Advanced Strategy.pptx
 
What is Swift? Features, advantages, and syntax basics
What is Swift? Features, advantages, and syntax basicsWhat is Swift? Features, advantages, and syntax basics
What is Swift? Features, advantages, and syntax basics
 
Which programming language should you learn next?
Which programming language should you learn next? Which programming language should you learn next?
Which programming language should you learn next?
 
10 reasons why swift is best for i os app development
10 reasons why swift is best for i os app development10 reasons why swift is best for i os app development
10 reasons why swift is best for i os app development
 
Swift App Development Company.pdf
Swift App Development Company.pdfSwift App Development Company.pdf
Swift App Development Company.pdf
 
Reasons to Choose Swift for iOS App Development.pdf
Reasons to Choose Swift for iOS App Development.pdfReasons to Choose Swift for iOS App Development.pdf
Reasons to Choose Swift for iOS App Development.pdf
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
Computer languages
Computer languagesComputer languages
Computer languages
 
Unit 4 Assignment 1 Comparative Study Of Programming...
Unit 4 Assignment 1 Comparative Study Of Programming...Unit 4 Assignment 1 Comparative Study Of Programming...
Unit 4 Assignment 1 Comparative Study Of Programming...
 
Hire expert swift developer
Hire expert swift developerHire expert swift developer
Hire expert swift developer
 
Introduction to java new
Introduction to java newIntroduction to java new
Introduction to java new
 
Introduction to java new
Introduction to java newIntroduction to java new
Introduction to java new
 
Different Programming Languages Analysed.pdf
Different Programming Languages Analysed.pdfDifferent Programming Languages Analysed.pdf
Different Programming Languages Analysed.pdf
 
Programming landuages
Programming landuagesProgramming landuages
Programming landuages
 
The different kind of programming language
The  different kind of programming languageThe  different kind of programming language
The different kind of programming language
 
Evolution Of Object Oriented Technology
Evolution Of Object Oriented TechnologyEvolution Of Object Oriented Technology
Evolution Of Object Oriented Technology
 
Top iOS App Development Tools That You Can Consider.pdf
Top iOS App Development Tools That You Can Consider.pdfTop iOS App Development Tools That You Can Consider.pdf
Top iOS App Development Tools That You Can Consider.pdf
 
What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...What is the best programming language to learn if you want to work on the blo...
What is the best programming language to learn if you want to work on the blo...
 
Java Programming Basics
Java Programming BasicsJava Programming Basics
Java Programming Basics
 

More from Aniruddha Chakrabarti

Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Aniruddha Chakrabarti
 
NLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryNLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryAniruddha Chakrabarti
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skillsAniruddha Chakrabarti
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsAniruddha Chakrabarti
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsAniruddha Chakrabarti
 
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTAniruddha Chakrabarti
 

More from Aniruddha Chakrabarti (20)

Pinecone Vector Database.pdf
Pinecone Vector Database.pdfPinecone Vector Database.pdf
Pinecone Vector Database.pdf
 
Mphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdfMphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdf
 
Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...
 
NLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryNLP using JavaScript Natural Library
NLP using JavaScript Natural Library
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Third era of computing
Third era of computingThird era of computing
Third era of computing
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skills
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflows
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows Platforms
 
CoAP - Web Protocol for IoT
CoAP - Web Protocol for IoTCoAP - Web Protocol for IoT
CoAP - Web Protocol for IoT
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
 
Level DB - Quick Cheat Sheet
Level DB - Quick Cheat SheetLevel DB - Quick Cheat Sheet
Level DB - Quick Cheat Sheet
 
Lisp
LispLisp
Lisp
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
memcached Distributed Cache
memcached Distributed Cachememcached Distributed Cache
memcached Distributed Cache
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Swift Apple Platforms

  • 1. 1Using Swift for All Apple Platforms Mphasis Using Swift for All Apple Platforms (iPhone, iPad, Apple Watch, Apple TV & Mac) A PoV by Aniruddha Chakrabarti AVP Digital, Mphasis Krishnaji Kulkarni AVP, Mobility Practice, Mphasis
  • 2. 2Using Swift for All Apple Platforms Mphasis Overview Apple introduced a new language called ‘Swift’ at the 2014 Worldwide Developers Conference (WWDC). Swift is a multi-paradigm, new generation programming language for development on all Apple platforms including iPhone (iOS), iPad (iOS), Apple Watch (watchOS), Apple TV (tvOS) and Mac (OS X) platforms. Swift incorporates the language innovations that have happened in the last two decades. Swift does not replace Objective-C, which was the programming language used across all the Apple platforms including iOS, watchOS, tvOS and OS X, but it completes Objective-C and other libraries like Cocoa Touch. Swift is a compiled programming language and belongs to the ‘C’ family of languages similar to C++, Java, C#, Objective-C and D. Swift is influenced by dynamic programming languages like Python, Ruby and functional programming languages like Haskell. Popularity of Swift After Apple introduced Swift at the 2014 Worldwide Developers Conference (WWDC), it has become widely popular within the developers community in just a year. According to TIOBE Index, November 2015, Swift ranks at 14th position for being the most popular language whereas Objective-C position has moved down drastically from 3rd to 15th in a span of just one year, clearly indicating that Swift is becoming the de-facto standard among developers. Programming language for Apple platforms including iPhone, iPad, Apple Watch, Apple TV and Mac (iOS, watchOS, tvOS and OS X). Swift has become so popular in just 18 months that it would not be wrong to say that it’s surpassing even the uptake of Sun Microsystems’ (now Oracle) Java programming language and Microsoft’s C# in the late 1990s and early 2000s. This PoV recommends the following guidelines: • For Greenfield systems and apps on iOS, watchOS, tvOS and OS X platforms, Swift should be used as the programming language • For Brownfield systems and apps (adding new features to existing apps) on iOS, watchOS, tvOS and OS X platforms, Swift along with Objective-C should be used as the programming language Note that this PoV does not cover all the features of Swift. It touches upon some of the important and prominent features that made Swift popular. iPhone (iOS) Apple Watch (watchOS) iPad (iOS) Apple TV (tvOS) Mac (OS X) Swift gained huge popularity among the developer communities within a year of its launch. Figure: TIOBE Language Index listing programming languages by popularity (December 2015) Dec 2015 Dec 2014 Change Programming Language Rating Change 1 2 Java 20.973% +6.01% 2 1 C 16.460% -1.13% 3 4 C++ 5.943% -0.16% 4 8 Python 4.429% +2.14% 5 5 C# 4.114% -0.21% 6 6 PHP 2.792% +0.05% 7 9 Visual Basic .NET 2.390% +0.16% 8 7 JavaScript 2.363% -0.07% 9 10 Perl 2.209% +0.38% 10 18 Ruby 2.061% +1.08% 11 32 Assembly Language 1.926% +1.40% 12 11 Visual Basic 1.654% -0.15% 13 16 Delphi/Object Pascal 1.405% +0.52% 14 17 Swift 1.405% +0.34% 15 3 Objective-c 1.357% -7.77%
  • 3. 3Using Swift for All Apple Platforms Mphasis Figure: TIOBE Language Index showing rise in the popularity of Swift language Historically, developers have used Objective-C for developing apps for iOS and OS X platforms. Objective-C, which is a superset of C with object-oriented constructs, was originally created by NeXT for its NeXTSTEP operating system in the 1980s. It lacks many of the new language design features invented and made popular in last three decades. Swift is Apple’s attempt to create a new, modern language for iOS, OS X, watchOS and new tvOS platforms. Swift Version 2 was released in WWDC 2015. Swift uses LLVM compiler infrastructure, which is a set of library files, re-usable low level tools and components for compilers. Languages that use LLVM includes Objective-C, Python, D, Scala, Ruby, R, Rust, Go and many more. LLVM infrastructure is also used for clang compiler - a new compiler for C, C++ and Objective-C. LLVM Project is jointly designed and developed by Vikram Adve and Chris Lattner. Currently, Chris Lattner works at Apple Inc. as the chief designer for Swift language. In 2012, both of them were awarded with the prestigious ACM Software System Award for breakthrough innovation and lasting influence in LLVM. In December 2015, Apple decided to make Swift as an open source platform by releasing the source code and library files to GitHub. Implementation of Swift on Linux (Ubuntu) is currently available at swift.org community site. Following Apple’s announcement, IBM ported Swift to Linux and introduced IBM Swift Sandbox, which is an online REPL (Read-eval-print loop) for executing small Swift code snippets. The Swift code, written in the online REPL, is executed on the Linux backend server and the results are then displayed in the web console. Advantages of Swift over Objective-C • Swift is designed with a philosophy ‘Simplicity is the Ultimate Sophistication’, so programs written in Swift are quite easier to read, write and maintain while compared to Objective-C programs • It’s built from ground up hence Swift incorporates the best-of-breed language design • Swift is much safer and faster than Objective-C • Swift supports Automatic Memory Management feature • As Swift requires less effort for coding/programming due to its low learning curve, it helps in yielding a good productivity graph at a faster rate • Swift has a low entry barrier and is easier to learn than Objective-C. Programmers, with background in other modern programming languages like Python, Ruby, C#, Java or Scala, easily learn Swift as they find many similar concepts. • Swift has better syntax when compared to Objective-C (though syntax is more of a personal preference, most of the programmers like Swift’s syntax more than Objective-C’s syntax). TIOBE Index for Swift Source: www.tiobe.com 1.75 1.5 1.25 1 0.75 .5 0.25 0 Jul' 14 Oct' 14 Ratings(%) Jan' 15 Apr' 15 Jul' 15 Oct' 15 In December 2015, Apple decided to open source Swift. Swift source code and libraries were released to GitHub. Implementation of Swift on Linux (Ubuntu) is currently available at swift.org community site.
  • 4. 4Using Swift for All Apple Platforms Mphasis In Swift, var keyword is used to declare a variable which is mutable and whose value can change throughout the life of the program var age = 30 age = 35 In Swift, let keyword is used to declare immutable values (or constants) let PI = 3.14 // Swift would not allow the below line and would give compile time error PI = 3.14159 2. Type Inference Swift tries to infer the type of a variable when you initialize it. Variables are declared using the var keyword and constants, using the let keyword. var lang = "Swift" // lang is inferred as String Though types are inferred, it’s also possible to annotate a variable with type information var lang: String = "Swift" // lang is explicitly declared as String If the declaration is missing initialization, then type information has to be supplied mandatorily var lang: String var lang // this statement is illegal and generates compiler error Swift can infer types for all types including String, Int, Double, Boolean etc. var org = "Mphasis" // org is inferred as String var age = 35 // age is inferred as Int let PI = 3.14159 // PI is inferred as Double let isFTE = true // isFTE is inferred as Boolean Type inference reduces the amount of code developers have to write. Though Swift uses Type Inference, it’s a statically, and not dynamically, typed language. So type inferred could not be changed later. var age = 35 // age is inferred as Int age = "Twenty" // Generates a compile time error Swift is a type-safe language - it performs type checks when the code flags any mismatched types as errors. 3. String Interpolation String Interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result that has the placeholders replaced by their corresponding values. var firstName = "Steve" var lastName = "Jobs" var age = 50 Salient Language Features of Swift 1. Immutability Though imperative programming languages support the concept of immutability (through constants), Functional Programming Languages suggest the use of immutability in many situations. Immutability comes as a great tool in parallel processing scenarios, as mutability is difficult to handle when multiple threads are trying to change the value of a variable. Type Inference Automatic Memory Management Generics Optional Closures First Class Functions
  • 5. 5Using Swift for All Apple Platforms Mphasis // String interpolation is used to embed variables within string literal print("My name is (firstName) (lastName) and I am (age) years old") // prints My name is Steve Jobs and I am 50 years old // Without string interpolation – prints the same output print("My name is " + firstName + " " + lastName + " and I am " + String(age) + " years old") 4. First Class Functions Swift supports First Class functions, which is a core tenant of Functional Programming. Functions are treated as first class objects. Functions could be assigned to a variable; declared as nested function; and can accept and return other functions. Nested Functions func complexCalc(a: Int, b:Int) -> Int { // square is a nested function declared within the parent function body func square(x: Int) -> Int{ return x * x } // Nested function declared before is invoked return square(a) + square(b) } print(complexCalc(10, b:20)) // prints 500 Functions can return another function func retFunc() -> (Int, Int) -> Int { func add(num1: Int, num2: Int) -> Int { return num1 + num2 } return add // retFunc returns add function } var delegate = retFunc() print(delegate(20, 30)) // prints 50 Functions can accept another function as parameter. This allows the function’s caller to provide some aspects of a function’s implementation when the function is called – this is very similar to Strategy or Template Method design pattern. This is very helpful for API developers. In the below example acceptFunc accepts a function that provides the calculation logic. func acceptFunc(calcFunction:(Int, Int) -> Int, a:Int, b:Int) { print("Result: (calcFunction(a, b))") } var addFunction = { (x:Int, y:Int) -> Int in return x + y } var mulFunction = { (x:Int, y:Int) -> Int in return x * y } acceptFunc(addFunction, a:10, b:20) // prints Result: 30 acceptFunc(mulFunction, a:10, b:20) // prints Result: 200 5. Internal and External Names of Function Parameters Just like Objective-C, Swift supports internal and external names for function parameters. A function parameter in Swift can have two names – an internal name, used within the function body to refer the parameter, and an external name of the parameter, used by the caller while calling the function.
  • 6. 6Using Swift for All Apple Platforms Mphasis In the below example add function accepts two Int parameters – the first parameter has an internal name of x, and the external name is num1. The second parameter has an internal name y, and the external name is num1. // add function declares different external and internal names for parameters // for the first parameter the internal name is x, while the external name is num1 // for second parameter the internal name is y, while the external name is num2 // internal parameter names are used within the function body // while external parameter names are used when invoking the function func add(num1 x:Int, num2 y:Int) -> Int { return x+y } print(add(num1: 20, num2: 10)) // prints 30 To keep the external parameter name same as internal _ could be mentioned as external parameter name. So in the below example the internal as well as external parameter names are same and function calls could be made without specifying the named parameter. func add(_ x:Int, _ y:Int) -> Int { return x+y } print(add(20, 10)) // prints 30 6. Enumerations Enumerations or ‘enums’ group related values and allows to work with these in a type safe way. Typically in languages that do not support enumerations, constants are used for this purpose but enums are type safe and improve the readability of the code. Below code example declares an enumeration called Animal that has three values Dog, Cat and Cow enum Animals { case Dog case Cat case Cow } let dog = Animals.Dog print(dog) let tiger = Animals.Tiger // compile time error since Tiger is not a member The values of the enum could be declared in the same line, separated by comma – enum Animals { case Dog, Cat, Cow } Individual enumeration values could be checked using a switch statement also - enum Animals { case Dog, Cat, Cow } var animal = Animals.Cow switch animal { case .Dog: print("The animal is Dog") case .Cat: print("The animal is Cat") case .Cow: print("The animal is Cow") }
  • 7. 7Using Swift for All Apple Platforms Mphasis 7. Tuples Tuples allow grouping multiple values into a single compound value. For example, employee name and age could be grouped together as a tuple. Tuples can contain any data types and any number of values, although typically it’s used for a pair of values. Below a tuple, called employee is declared with two elements – a String and an Integer. It’s called a Tuple with type (String, Int) var employee = ("Bill", 35) // employee is a tuple with two elements Individual elements of a tuple could be accessed as tuple.index numbers with index starting at 0 print(employee.0) // prints Bill print(employee.1) // prints 35 Individual elements of a tuple could be named while declaring it, though it’s optional. Typically, in functional programming languages, tuple elements are not named to keep the syntax minimal. var employee = (name: "Bill", age: 35) // first element of the tuple is name and second element is age If individual elements are named then they could be accessed using the tuple.element syntax print(employee.name) // prints Bill print(employee.age) // prints 35 Tuples could have more than two elements var employee = ("Bill", 35, 1234.55, true) print(employee.2) print(employee.3) One interesting use case of Tuple is, it allows to return multiple values from a function. func addAndSubtract(num1: Int, num2: Int) -> (Int,Int) { return (num1 + num2, num1 - num2) } print(addAndSubtract(20, num2:10)) // prints (30, 10) Tuple’s elements could be decomposed using multiple variable declaration func addAndSubtract(num1: Int, num2: Int) -> (Int,Int) { return (num1 + num2, num1 - num2) } let resTuple = addAndSubtract(20, num2:10) let (addRes, subRes) = resTuple // decompose tuples elements into individual variables print(addRes) // prints 30 print(subRes) // prints 10 8. Type Aliases Type aliases allows to define an alternative name for an existing type. Later, new variables are eligible to use a new alternative name. // declare a Type alias alternate type EmployeeId for UInt16 typealias EmployeeId = UInt16 // While declaring the variable use the Type alias alternate type var id: EmployeeId id = 2 print(id) // prints 2 Type aliases could be used for complex types as Tuple also // declare a Type alias for a Tuple of type String, Int to hold name and age typealias Employee = (String, Int)
  • 8. 8Using Swift for All Apple Platforms Mphasis // While declaring the variable use the Type alias alternate type var emp: Employee emp = ("John", 55) print(emp.0) // prints John print(emp.1) // prints 55 9. Optional Type and Optional Chaining Swift supports Optional Types that handles the absence of a value. Using optionals is similar to using nil with pointers in Objective-C, but they work for any type, not just classes. The options help avoid unnecessary nil checks before accessing the objects. So value of an Optional type would either be some value or nil. Optional types are declared by marking ? after type name. var age: Int? // age is declared as Int? or optional int print(age) // since it’s not initialized to any value, it’s value is nil age = 10 print(age) // prints 10, since it’s initialized to value 10 The optional type wraps the variable and to access these objects, operator ‘!’ used to forced unwrapping & getting the underneath value. This can also be achieved by using implicit wrapping, while defining, as below. var name: String! // Name is implicit unwrapping of the optional name variable print(“Name is (name)”) // since it’s not initialized to any value, it’s value is nil name = "Anamika" print("Name is (name)") // prints “Name is Anamika” since initialized Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. class Employee{ var firstName: String = "" var lastName: String? // lastName property is optional var designation: String = "" var address: Address? // Optional chaining – Address is optional init(firstName: String, designation: String, address: Address?){ self.firstName = firstName self.designation = designation self.address = address } } class Address{ var streetAddress: String? // streetAddress property is optional var city: String = "" var country: String = "" init(city: String, country: String){ self.city = city self.country = countr } } var add = Address(city: "Mpls", country: "USA") var emp = Employee(firstName: "John", designation: "Architect", address: add) print("Name - (emp.firstName) (emp.lastName)") // prints Name - John nil as lastName property is nill print("Address - (emp.address!.streetAddress) (emp.address!.city) (emp.address!.country)") // prints Address - nil Mpls USA as Address.streetAddress property is nill
  • 9. 9Using Swift for All Apple Platforms Mphasis 10. Closures Closures are anonymous functions or self-contained blocks of functionality. Closures could be returned or passed as parameters to named functions. They could be assigned to variables. Closures in Swift are similar to blocks in C and Objective-C, and to lambdas or anonymous functions in other programming languages like C# and Java. Below is an example of closure or anonymous function. Here the closure is assigned to the variable add - let add = { (x:Int, y:Int) -> Int in return x + y } print(add(20,10)) // prints 30 This could be further simplified by taking advantage of type inference. In the below example types of x and y parameters are inferred - let add = { x, y -> Int in x + y // same as return x+y, return is optional for last statement } print(add(20,10)) // prints 30 The function body could be further simplified by writing in the same line – let add = { x, y -> Int in x + y } print(add(20,10)) // prints 30 Collection class functions like sort, filter and map accept closure as parameters. Following code snippet uses sort function that accepts a closure to sort an array - let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"] var sortedCities = cities.sort( { (s1:String, s2:String) -> Bool in return s1 < s2 }) print(sortedCities) // prints ["Bangalore", "Chennai", "Delhi", "Kolkata", "Mumbai"] Following code snippet uses filter function that accepts a closure to filter cities that start with “B” - let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"] var filteredCities = cities.filter({(str:String) -> Bool in return str.hasPrefix("B")}) print(filteredCities) // prints ["Bangalore"] Swift automatically provides shorthand names for arguments to inline closures - $0, $1, $2 ... $n etc. These refer to the values of the closure’s arguments and need not be declared explicitly, so the sort could be simplified as – let cities = ["Kolkata", "Bangalore", "Chennai", "Mumbai", "Delhi"] var sortedCities2 = cities.sort( { $0 < $1 } ) print(sortedCities2) // prints ["Bangalore", "Chennai", "Delhi", "Kolkata", "Mumbai"] 11. Properties Properties are class level instance variables on steroid. In languages, that do not support Properties, instance variables are made private (or protected) so that clients outside the class cannot assign invalid value to the instance variable. For setting and getting values of class members, setter and getter methods are used. Properties support this principle formally through language. Other programming languages, like C#, also support properties as language feature. In the below example Age is the property of class Employee, the type of Age is Int. The property has both a getter and a setter - class Employee { private var _age : Int = 0
  • 10. 10Using Swift for All Apple Platforms Mphasis var Age: Int { get { return _age } set { if newValue < 0 { print("Age cannot be negative") } else{ _age = newValue } } } } var emp = Employee() emp.Age = -10 // prints Age cannot be negative emp.Age = 30 print(emp.Age) // prints 30 12. Subscripts Subscripts are widely used to access elements of a collection type like Array, sets and dictionary using the familiar collection[index] syntax. Subscripts provide shorthand for getting and setting values of the elements of a collection. In the below example, a class called Employees is defined, which can hold name of multiple employees. Employees class allows getting and setting employee names for a specific index using Subscripts. Subscript syntax is similar to property syntax – The subscript can have both a getter and a setter. class Employees { var _emps = [String]() func add(name: String) { _emps.append(name) } var count: Int { get { return _emps.count } } subscript(index: Int) -> String { get{ return _emps[index] } set(newValue) { _emps[index] = newValue } } } var employees = Employees() employees.add("Aniruddha") employees.add("Bill") employees.add("Krishna")
  • 11. 11Using Swift for All Apple Platforms Mphasis print(employees.count) // prints 3 print(employees[1]) // prints Bill. Gets the employee at index 1 employees[1] = "Steve" // Sets the employee an index 1 print(employees[1]) // prints Steve. Gets the employee at index 1 13. Operator Overloading Operator overloading is a key feature provided by most of the Object Oriented languages, including C++. Swift supports operator overloading, which allows to change or redefine existing operators’ work for classes or structures. For example, Swift’s built-in String class does not provide an implementation of multiplication (*) operator. So the below code generates a compile time error – print("Aniruddha" * 4) // compile tile error But it’s possible to provide implementation of multiplication operator of built-in String class so that it adds the string value to number of times. So “a” * 5 would result in “aaaaa” - // * or multiply operator overloaded for String // This would be invoked when the sequence is String * Int func * (value: String, no: Int) -> String { var result = "" for var ctr = 0; ctr < no ; ++ctr { result += value } return result } print("Aniruddha" * 4) // prints AniruddhaAniruddhaAniruddhaAniruddha 14. Extension Extension is a unique feature of Swift, which adds new functionality to an existing class, structure, enumeration, or protocol type. Using Extension, even classes for which source code is not available could be extended – examples are library classes or built in classes like String or Int. Objective-C has a similar feature called categories, but other C family languages do not support the same. Extension is a very powerful mechanism and directly supports Open Closed Principle (OCP) of SOLID object oriented principles. import Foundation // Built in String class is extended and a toUpper() method is added extension String{ func toUpper() -> String { return self.uppercaseString } } // Built in String class is extended and a toLower() method is added extension String{ func toLower() -> String { return self.lowercaseString } } var city = "Bangalore" // Added extended methods on String are invoked print(city.toUpper()) // prints BANGALORE print(city.toLower()) // prints bangalore
  • 12. 12Using Swift for All Apple Platforms Mphasis 15. Protocols Protocols are equivalent of Interface or Contracts in other programming language. A Protocol defines the signatures of methods, properties, and other requirements for a class, structure or enumeration. Protocols do not contain the implementation - class, structure or enumerations adopt the protocol and provide the implementation of the contract or blueprint defined in the protocol. In the below example, class Bird adopts or implements both Flyable and Runnable protocols whereas class Human adopts only Runnable protocol - protocol Flyable{ func fly() } protocol Runnable{ func run() } // class Bird is adopting Flyable and Runnable protocols class Bird : Flyable, Runnable{ func fly(){ print("I can fly") } func run(){ print("I can run too") } } // class Human is adopting Runnable protocol class Human : Runnable{ func run(){ print("I can run") } } var bird = Bird() var human = Human() bird.fly() // prints “I can fly” bird.run() // prints “I can run too” human.run() // prints “I can run only” Protocols can specify methods, properties, initializers (also called constructor in other languages) etc in the definition. 16. Generics // Declare a generic function that accepts parameters of any type, swaps them // and returns the swapped value as Tuple. func swap<T>(arg1: T, arg2: T) -> (T, T) { return (arg2, arg1) } var resInt = swap(10, arg2:20) print(resInt) // prints (20, 10) var resDbl = swap(100.50, arg2:576.6789) print(resDbl) // prints (576.6789, 100.50) var resStr = swap("Hello", arg2:"World") print(resStr) // prints ("World", "Hello")
  • 13. 13Using Swift for All Apple Platforms Mphasis 17. Swift Standard Library Swift Standard Library defines a base layer of functionality for writing Swift programs – it contains fundamental data types, common data structures, base protocols, commonly used function etc. It is similar to .NET BCL (Base Class Library) or Java Class Library which abstracts and contains similar features. The Swift Standard Library consists of – • Basic data types like Int, String and Double • Common data structures such as Array, Dictionary and Set • Common functions and methods like print • Protocols that describe abstractions such as Comparable (used for comparing types), Equatable (base protocol for comparing for value equality using operators == and !=) and Streamable (base protocol for providing text streaming functionality) as well as other standard base protocols Other differences between Swift and Objective-C • Typically in C family languages, including Objective-C, statements need to end with ‘;’. In Swift, statements need not have ‘;’ at the end (similar to JavaScript) • Header files are not required in Swift • Swift supports new features like type inference, generics, first class functions, tuples etc., which are not present in Objective-C • Pointers are not exposed by default in Swift while Objective-C supports pointers • Strings in Swift fully support Unicode. Even variable names support Unicode • Swift supports operator overloading • String handling is much easier and elegant in Swift in comparison to Objective-C Conclusion Swift has attained great popularity among developers community in just one year. It is a modern, fast and fun-to-learn programming language, designed for mobile and cloud scenarios. There are many advantages of using Swift over Objective-C. For all Greenfield apps, Swift is fast becoming the de-facto standard for all Apple platforms including iOS, watchOS, tvOS and OS X. We envision that Swift would play a huge role in future Apple projects like VR headset, Connected Car, and health band. We believe Swift would play a dominant role in not only Apple platforms, but could also become a significant programming language across varied platforms. After Apple open sourced Swift, there has been wide interest in implementing Swift in other platforms, like Linux as well as in other non-Apple platforms. We also see a community being built up around Swift. Swift Standard Library defines a base layer of functionality for writing Swift programs – it contains fundamental data types, common data structures, base protocols, and commonly used function, etc. For all Greenfield apps, Swift is fast becoming the de-facto standard for all Apple platforms including iOS, watchOS, tvOS and OS X.
  • 14. 14Using Swift for All Apple Platforms Mphasis References Overview of Swift (Wikipedia) - https://en.wikipedia.org/wiki/Swift_(programming_language) LLVM - https://en.wikipedia.org/wiki/LLVM Swift Language Guide - https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ TheBasics.html Swift Standard Library - https://developer.apple.com/library/ios//documentation/General/Reference/SwiftStandardLibraryReference/index.html Open Source Swift Community – http://swift.org Public source code of Swift - https://github.com/apple IBM Swift Sandbox / REPL - http://swiftlang.ng.bluemix.net/#/repl Swift 3.0 and future enhancements - https://github.com/apple/swift-evolution Copyright ©: The brand names mentioned in this PoV (Apple, Swift, iOS, OS X, iPhone, iPad, Apple Watch, Apple TV, Mac, Objective-C, etc.) belong to their respective owners.
  • 15. 15Using Swift for All Apple Platforms Mphasis Aniruddha Chakrabarti Associate Vice President, Digital, Mphasis Aniruddha possess 16 years of IT experience spread across systems integration, technology consulting, IT outsourcing, and product development. He has extensive experience of delivery leadership, solution architecture, pre-sales, technology architecture, and program management of large scale distributed systems. As AVP, Digital in Mphasis Aniruddha is responsible for Presales, Solution, RFP/ RFI and Capability Development of Digital Practice. Prior to joining Mphasis he has played various leadership and architecture focused roles in Accenture, Microsoft, Target, Misys and Cognizant. He has been Lead Architect for many large scale distributed systems. His interests include digital, cloud, mobility, IoT, distributed systems, web, open source, .NET, Java, programming languages and NoSQL. His industrial experience spans across different verticals such as: Retail, Healthcare, Capital Markets, Insurance, Travel, Hospitality, Pharma and Medical Technology. Krishnaji Kulkarni Associate Vice President, Mobility Practice, Mphasis Krishnaji Kulkarni has 20+ years of IT experience, having involved in architectural and delivery solutions for large scale projects/programs across industry verticals. His experience spreads across mobility, Systems Integration (SI), business process automation and web technologies. As AVP & Lead - Mobility Practice in Mphasis, he is responsible for pre-sales, RFP/RFI solution architecting, practice capability building and the SME support to the delivery teams. In the last couple of years, he had closely worked with leadership of key accounts to nurture digital transformation opportunities and played an instrumental role in building into successful long-term relationships.
  • 16. 16Using Swift for All Apple Platforms Mphasis VAS21/03/16USLETTERBASIL3849 For more information, contact: marketinginfo@mphasis.com USA 460 Park Avenue South Suite #1101 New York, NY 10016, USA Tel.: +1 212 686 6655 Fax: +1 212 683 1690 Copyright © Mphasis Corporation. All rights reserved. UK 88 Wood Street London EC2V 7RS, UK Tel.: +44 20 8528 1000 Fax: +44 20 8528 1001 INDIA Bagmane World Technology Center Marathahalli Ring Road DoddanakundhiVillage,Mahadevapura Bangalore 560 048, India Tel.: +91 80 3352 5000 Fax: +91 80 6695 9942 About Mphasis Mphasis is a global Technology Services and Solutions company specializing in the areas of Digital and Governance, Risk & Compliance. Our solution focus and superior human capital propels our partnership with large enterprise customers in their Digital Transformation journeys and with global financial institutions in the conception and execution of their Governance, Risk and Compliance Strategies. We focus on next generation technologies for differentiated solutions delivering optimized operations for clients. www.mphasis.com