Akshaykumar Patel
No. of student’s record book w58016
iOS Development with Swift programming language
Supervisor: academic degree, dr Andrzej szelcMASTER THESIS AT SECOND-CYCLE STUDIES
Rzeszów 2018
A statement of the following content, legibly undersigned by the author of the thesis:
I, the undersigned, hereby state that the thesis entitled “……………………………..” submitted by me has been prepared without any help and does not infringe on anyone’s copyright.
I also state that the thesis has not been subject to procedures connected with acquiring an academic (Bachelor’s, Master’s) degree at a higher education institution at any earlier time.

Moreover, I declare that this version of the thesis is identical with the submitted electronic version.


Dateauthor’s legible signature
A statement of the following content, legibly undersigned by the supervisor of the thesis:
I declare that this thesis has been prepared under my direction, and I state that it fulfills the conditions for presenting it in proceedings for acquiring an academic (Bachelor’s, Master’s) degree.


Datesupervisor’s legible signature

Table of Contents
TOC o “1-3” h z u
ACKNOWLEDGEMENT1ABSTRACT2OBJECTIVE3METHODOLOGY3CHAPTER 1 Introduction of iOS41.1 About iOS41.2 iOS application architecture61.3 About Xcode – Apple native integrated development environment.71.4 Comparision with other languages8CHAPTER 2 iOS development with swift 4.182.1 About swift language.82.2 Explaination of code92.3 Advantages of swift programming language PAGEREF _Toc486883787 h 102.4 MVC pattern of iOS development. PAGEREF _Toc486883788 h 10CHAPTER 3 Evalution of swift PAGEREF _Toc486883790 h 183.1 Speed PAGEREF _Toc486883792 h 183.2 Features set PAGEREF _Toc486883793 h 183.3 Safety PAGEREF _Toc486883794 h 19CHAPTER 4 Introduction of SpritKit framework PAGEREF _Toc486883799 h 274.1 configure basic device settings PAGEREF _Toc486883800 h 274.2 Saving the basic running configuration for all three routers PAGEREF _Toc486883801 h 324.3 Verify the Site-to-Site IPsec VPN Configuration PAGEREF _Toc486883802 h 354.4 Verify the IPsec VPN Operation PAGEREF _Toc486883803 h 35CONCLUSION PAGEREF _Toc486883804 h 40LITERATURE PAGEREF _Toc486883805 h 41List of abbreviation PAGEREF _Toc486883806 h 42SUMMARY PAGEREF _Toc486883807 h 43
I express my sincere gratitude to my advisor, Prof. Andrzej szelc of the University of Information Technology and management of Rzeszow, for his unlimited patience as well as guidance and encouragement. None of the work described in this thesis would have been possible without his invaluable technical and moral support.
During my thesis time at, I have had the pleasure of working with study. I owe my colleague Mr.Dharmesh Makarubiya a sincere debt of gratitude for his help with the implementation of the code described in this thesis, for his many useful pieces of advice. I would also like to thank Mr.Bhagwan Mangukiya for many suggestions about the work described in this thesis and for several extremely interesting discussions about sprite kit framework, also for his infinite wisdom and smartness. I am grateful to my universities’ friend for creating a fun work atmosphere.
Finally, I would like to thank my family. I owe my parents for a huge debt of gratitude for the unconditional support and discontinuous encouragement, which they have always given me. I am deeply indebted to my grandparents for always cheering me up regardless of how bad things seemed. This accomplishment would not have been possible without them.

Since 2007, Apple introduced various models of handheld devices including iPhone, iPad, iPod and Apple Watch which provide a potential market for applications. As a result, iOS development becomes a significant topic for developers around the world to explore and study in detail, Consequently, this thesis also focuses on how to create an iOS application using swift language with sprite kit framework animation..
The goal of the research is to learn how to develop an iOS application within supportive environment and Swift programming language from Apple. Nowadays, many programming language release for safe and secure code, swift is one of them. I describe full architecture of iOS as well as how to create swift application using Xcode. Currently, swift 4.1 introduce by apple, so here I explain some new features of the version 4.1. Also, I will give you one of small example how to make simple game using sprit kit framework with help of swift development. This app is related to like break the fruits with help of gesture recognize. Actually, sprite kit framework is most useful for game animation in iOS, also lots of companies use this framework for develop gaming application nowadays. I think that in future there will be lots of new libraries and feature in sprit kit framework.
In the future, swift will more powerful language because of the fastest execution and security. Also, swift has more secure in build libraries for core location, message kit, push notifications etc.

OBJECTIVEHow to developer iOS application using swift.How to make game animation using sprit kit framework with swift.

Future of swift.

METHODOLOGYIn my thesis, I used books and websites as material. I take more reference from apple developer official site. In this thesis I take all example which is written by me. I research on more swift because I think it will be best programming language in future because of its’ features and libraries.

iOS iPhone Operating System
2D 2-dimensional
3D 3-dimensional
App Application
WWDC Apple Worldwide Developers Conference
iPADiOS-based line of tablet computer
Mac Macintosh
Apple TV A digital media player and a micro console
Apple Watch Smartwatch developed by Apple
GPU Graphics Processing Unit
OpenGL Open Graphics Library
IDE Integrated Development Environment
LLVM Low Level Virtual Machine
Cocoa Touch User Interface framework for building software programs to run on iOS

CHAPTER 1 Introduction of iOS
1.1 About iOS
In the beginning, Apple Computer Inc. introduced their first iPhone on 2007, which created a big revolution for Smartphone industry with a big touchscreen and one home button for navigation. iPhone is the first user-friendly smartphone designed to gives their users a comfortable feeling when surfing web content, exploring applications with simple touches as well as various standard mobile phone features. Besides, iPhone allows users to touch the contents while, at the time, there are few companies can. According to Goadrich and Rogers (2011), iOS development is getting more and more popular over the time, which aims to create applications selling on App Store and can be applicable for iPhone or iPad’s users. In the first three months of 2017, Apple is having 42.7 percent of users from all the gadgets and mobile market while Android shares more than 50 percent and other mobile companies’ shares are just over 2 percent of the market (Wee, 2017). Moreover, in 2017, the number of downloads through Apple store reaches 25 billion which is unreal and a milestone for company (Apple 2015, cited 22.02.2017).
Released in June of 2014 by Apple Swift is a statically typed language and compiled language that uses the LLVM compiler infrastructure and the Objective-C runtime. Since Swift uses the same runtime as Objective-C the two languages can be intermixed in a single program or project, as both will compile down to native machine code. Swift can access Objective-C classes, types, functions, and variables through a “bridging header”, as well as by extension C and C++ code. Similarly, Objective-C can access code written in Swift, with some exceptions. This allows Swift to work with the Cocoa and Cocoa Touch frameworks and existing Objective-C apps and libraries without rewriting the large body of code that was written for iOS devices. Swift is heavily influenced by many other languages such as Rust, Haskell, Ruby, Python, and C#, and offers many of the object-oriented and functional features found in these languages. Swift also includes a read-eval-print-loop (REPL) that can be accessed in Xcode as well as on the command line.
As Objective-C aged it became harder for new developers, unfamiliar with C and SmallTalk, to learn and understand. Languages such as Java, Python, and Javascript became widely used and began to set the standard for modern programming languages. Developers began to complain that Objective-C was difficult to learn and uncomfortable to use. This difficulty made fewer developers interested in making iOS and OS X applications and several began to switch over to Android operating system, which allowed them to write in Java. However Apple could not switch which language it supported without rewriting the Cocoa and Cocoa Touch frameworks, as well as abandoning any legacy Objective-C code. Apple needed a way to use a different language while simultaneously continuing to support all of its Objective-C code.
Swift had been a closely kept secret up until its announcement, and came as a surprise to the developer community. Since switching programming languages is a nontrivial task for individuals and organizations, Apple needed to demonstrate that Swift was worth the additional overhead. During the WWDC presentation Apple claimed that the language would run significantly faster than Objective-C, and would be a modern programming language with all the features common to other recent programming languages. They also claimed it would be extremely safe language that eliminated many classes of unsafe code. Finally, the language would be easy to learn and use.
I test each of these claims as best I can in order to develop a better idea of how Swift will be used by the average programmer. I first use two different algorithms to benchmark Swift against four other languages to determine in general how fast Swift runs. I then take the major features of Swift and see if I can find other language that have the same features. Finally, I create my own iOS application in Swift to demonstrate using the language for nontrivial tasks. I find that while Swift generally runs faster than Objective- C it is difficult to reproduce the exact speedup projected by Apple. I also discover that Swift has almost all the features commonly found in a modern programming language, with the exception of exception handling, native support for parallelism and concurrency, and optional types.
Eventually, I find that Swift is easy to use, has a pleasing syntax, and eliminates many types of programming errors. However, there are some difficulties in using Swift that result from interacting with Objective-C code and the Cocoa Touch APIs. Overall I conclude that Swift is a dramatic improvement from Objective-C and hopefully the rough edges will be smoothed out over time.
Therefore, the aim of this thesis is to explain how to develop an iOS application. The development will apply XCode 9 which is an Integrated Development Environment (IDE), where developers can create, test and debug apps using Swift 4.1 as the main programing language. At last, the testing phase will be accomplished manually to make sure that the application can work properly and smoothly. Practicing the knowledge from the research, an iOS application code as well as small game code will be developed.
1.2 iOS application architecture
From starting, iPhone operating system, best known for iOS, was introduced alongside with iPhone by Apple Inc. on 2007 (Gonzalez-Sanchez and Chavez-Echeagaray, 2010). iOS is exclusively designed and distributed by Apple and pplication is developed within supported environment. The environment, in this case, is not only considered as a place to develop application but also the whole ecosystem, that will start from the lowest level of knowledge called Cocoa touch layer. In order to utilize the best out of Cocoa touch layer, XCode native IDE from Apple and Swift programming language will be used accordingly.
Apple has continued to utilize iOS for iPod Touch, iPad, Apple TV and Apple Watch. Thus, iOS is continuously developed and enhanced. However, the most basic technology is kept, which includes three layers of system: Cocoa Touch layer, Media layer and Core layer. The Core layer has two sub layer called Core Services layer and Core OS layer (Apple 2014, cited 22.02.2017).
FIGURE 1 iOS Architecture
The Cocoa touch layer (figure 1) can be considered as the user interface and user experience. It provides huge variety of components and design methodologies from Apple, including multitasking, touch-based input and output, notifications, and high-level system interactions. Therefore, Cocoa touch layer is the most fundamental layer of iOS application (Apple 2014, cited 22.02.2017).
Media layer provides various multimedia functionalities, including video, auto and graphics. Graphics technologies content numerous embedded libraries which enhances iOS applications’ high-quality user interface and easy to customize due to its flexibility. Audio technologies, on the other hand, come with hearing experiences. Audio technologies support rich audio playback, audio recording, HDMI content and built-in sounds. Finally, video technologies utilize the power of iPhone to manage video contents such as playing and recording. Besides, with appropriate recording hardware, video technologies can also provide the ability for streaming video contents through internet.
As mentioned earlier, the Core layer has two sub layer called Core Services layer and Core OS layer. Core services layer is the layer for adding peer-to-peer services, such as iCloud, social media sharing and networking. iCloud, or iCloud storage, is the Apple’s online data storage. iCloud service provides functionalities for writing user documentations and information to a central location. iCloud storage is protected by Apple at an extremely high-level of security so that users’ data will not be stolen or leaked. On the other side, Core OS layer is the low-level layer which provides back-end processing functionalities. Core OS provides frameworks which support upper level layers with security and management. Managing functionalities are, mainly, local authentication, core Bluetooth, external assessor and network extension.
1.3 About Xcode – Apple native integrated development environment
XCode is an integrated development environment introduced by Apple in 2003. The latest and most stable version of XCode is version 8 (figure 2). XCode comes with modern yet powerful features which provide a full package for developers. XCode gives developers a supported UI designing, implementing and testing. The most powerful feature of XCode is runtime, which continuously tracks and alert developers about syntax bugs, designing recommendations and memory management. Additionally, with the latest version, XCode provides large amount of extensions which can be smoothly integrated into the application (Apple 2015, cited 22.02.2017).

XCode supports various types of programming languages and script writing including C, C++, Objective-C, Objective-C++, Java, AppleScript, Python, Ruby, ResEdit and Swift. Despite of huge amount of programming languages supported, Apple decided to make Swift as the main programming langue for XCode (Apple 2017, cited 22.02.2017).
Interface builder is an editor within XCode. Interface builder supports drag and drop feature without coding which gives developers easier tasks for designing the user interface. Because of the Cocoa and Cocoa touch objects, developers can design user interface separately from implementation. Moreover, the connection between UI and code will be handled by integrated runtime. The connection, which can be considered as a label, allows developers to manipulate the UI components with controller. The runtime will notice developers instantly when the object is placed wrong or the conflict between object and logic behind.
1.4 Comparison with other languages
Generally, network measure is imperative, in light of the fact that the bigger a programming dialect network is, the more help you’d probably get. As you venture into the programming scene, you’ll before long see how fundamental help is, as the designer network is tied in with giving and getting help. Also, the bigger a network, the more individuals will fabricate helpful apparatuses to make improvement in that specific dialect simpler. Starting at now, there are more than 600 outstanding programming dialects around the world. Thus, in light of that unique circumstance, how about we dive into the subtle elements of the Swift people group estimate.

FIGURE 3 Language comparision
CHAPTER 2 iOS development with Swift 4.1
2.1 About Swift Language
In the beginning, Swift is a programming language created by Apple and was developed from objective-c. However, Swift is more modern and user-friendly language that is designed for users and by users. It has both the power of low-level programming languages like C or C++ and the smoothness of high-level languages like C# or JavaScript. Moreover, Swift is light and packs with pre-defined library. “The goal of the Swift project is to create the best available language for users ranging from systems programming, to mobile and desktop apps, scaling up to cloud services.”, stated Apple Inc (2017).
Swift has several features and characteristics which provide the best environment for developers. The main three key elements that help Swift stands out from the crowd are safe, fast and expressive. Runtime, as mentioned above, is the built-in debugger, which can track and alert developers spontaneously. Thanks to Runtime, Swift can provide the safe and user-friendly environment for developers. Besides, Swift is developed from C-based languages, such as C, C++ and Objective-C so it inherences all the best and improvement from C-base family. Thus, Swift is predicable, consistent and fast as well as expressive since it is the modern programming language which has been developing for years (Apple 2015, cited 22.02.2017).
The learning process for Swift is rather painless. Programmers familiar with C type languages like Java and C++ will quickly feel comfortable in Swift, as much of the syntax and programming style is the same. I was quickly able to write basic scripts in swift and feel comfortable with most of the language concepts in a day or two. Having no prior experience in Objective-C did not seem to have any impact on my ability to pick up Swift, since Swift feels closer to Java and Scala than Objective-C. The only difficulty that arose from not knowing Objective-C is that most tutorials and guides are still written from Objective-C and it is challenging to find quality resources for Swift. The other challenge while learning to build SwiftDraw was learning to interact with the Cocoa Touch APIs. This turned out to be one of the more difficult aspects of working with Swift.
The advantage for Apple of creating a new language is that Swift can access the Cocoa APIs without having to rewrite any of the Objective-C code that already exists. The downside to this is that because the APIs were not originally written for Swift, there is additional work on the programmer’s part to convert them to Swift. Many of the Cocoa Touch API methods can possibly return null, or return the general type AnyObject. This requires heavy use of optionals and typecasting. While not overly difficult, this does make the code littered with optionals and question marks, making it difficult to decipher what is an optional and what is not. In many cases I ended up casting everything to an implicitly unwrapped optional so I did not have to constantly unwrap everything.
Additionally, some of the Cocoa Touch methods require Objective-C objects such as NSObject or AnyObject which makes them harder to use. It can be difficult to work within the rules of typecasting in Swift when you need to turn a String into an AnyObject type. Strings are not objects in Swift, and therefore must be cast toNSStings before being cast to AnyObject. Additionally, there are three different type casting operators in Swift, despite all looking identical. Overall the Cocoa Touch API adds many complex layers of casting and optionals that are difficult to decipher. This can be avoided by simply force casting to an implicitly unwrapped optional, but then many of the safety guarantees in Swift are lost.
This overuse of the implicitly unwrapped optional continues because of the two stage initialization process. Every variable needs to have a value either at the top of the class or in the init method, or be declared an optional. Because often its desirable to have variables initialized during the ViewDidLoad method in order to access the self.view attribute, most variables become implicitly unwrapped optionals. This opens up a program to null pointer errors which is exactly what Swift was trying to avoid with two stage initialization.
There were also issues when dealing with protocols in Swift that I dis- covered while implementing the composite design pattern, which requires an array of mixed types that share a prototype. I created the protocol Shape and two classes, square and circle, which both implement Shape. I then declared an array of shapes and tried to find the first instance of a spe- cific shape. The first difficulty was that to find an element in an array Swift uses a global method, rather than a method defined on the array class. That makes it difficult to use code completion in Xcode because you need to know exactly what the method name is before you call it. The second difficulty was that in order to find an element in an array that element must extend the Equatable protocol. This requires that the == method be overloaded at global scope, rather than being contained in the class. However Swift does not allow the == method to accept a protocol as a parameter, which means the Shape protocol cannot extend Equatable and therefore it is impossible to have an array of protocols in Swift.
There are also a few things that should work in Swift that seem to be broken. Several methods on Strings, such as containsString or length, are included in the documentation but do not work in the language. In order to access several of the methods the String must be cast to the Objective-C type NSString. Additionally Swift types are supposed to be available when defining Core Data objects, however this functionality remains unavailable. These bugs may be fixed in future updates to Swift. Several other bugs and features changed during the course of this project. When I first began writ- ing SwiftDraw Immutable arrays initially could be modifier and there was no Set collection type despite being in the documentation. These bugs were fixed near the end of the project during a large update to Swift. Additional features were added as well such as access control, failable and forced op- tional type casting, and multiple optional unwrapping. This update broke some of the code I was working on, and changed how I implemented cer- tain patterns in the language. While the changes were middle annoying, this shows that Apple is continuing to iterate and improve Swift, and the language will continue to get better.
On the positive side, writing Swift is generally a pleasure due to the many syntactic sugars in the language. Combined with the heavy use of type inference and the lack of semicolons, Swift feels closer to a scripting language than a systems language. It is a slight disappointment that list comprehensions are not included in Swift, although the map and filter syntax is easy to use. For all the trouble that optionals cause, they do make it easy to check for null variables quickly, and can even be chained together which leads to cleaner code. Swift also keeps the style of method names from Objective-C, giving each method a long descriptive name that can have internally and externally named parameters. This helps separate internal use of a variable from its meaning when called externally and is quite helpful.
2.2 Explanation of code
Some other features that can be seen as an advantage of Swift are worry-free syntax, inferred style variable and nested comment style. There are a number of language improvements in this release, including conditional conformance, recursive constraints on associated types in protocols and more.

In term of worry-free syntax, developers do not need to remember the semicolon at the end of every single code line as in C++, Python or Objective-C, which can give developers more time and confidence when developing an application.

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it’s defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values.

Data types that are normally considered basic or primitive in other languages—such as types that represent numbers, characters, and strings—are actually named types, defined and implemented in the Swift standard library using structures. Because they’re named types, you can extend their behavior to suit the needs of your program, using an extension declaration, discussed in Extensions and Extension Declaration.

A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types. A compound type may contain named types and other compound types. For instance, the tuple type (Int, (Int, Int)) contains two elements: The first is the named type Int, and the second is another compound type (Int, Int).

You can put parentheses around a named type or a compound type. However, adding parentheses around a type doesn’t have any effect. For example, (Int) is equivalent to Int.

This chapter discusses the types defined in the Swift language itself and describes the type inference behavior of Swift.

type ? array-type
type ? dictionary-type
type ? function-type
type ? type-identifier
type ? tuple-type
type ? optional-type
type ? implicitly-unwrapped-optional-type
type ? protocol-composition-type
type ? metatype-type
type ? Any
type ? Self
Type Annotation
A type annotation explicitly specifies the type of a variable or expression. Type annotations begin with a colon (:) and end with a type, as the following examples show:
let someTuple: (Double, Double) = (3.14159, 2.71828)
func someFunction(a: Int) { /* … */ }
In the first example, the expression someTuple is specified to have the tuple type (Double, Double). In the second example, the parameter a to the function someFunction is specified to have the type Int.

Type annotations can contain an optional list of type attributes before the type.

type-annotation ? : attributes opt inoutopt type
Array with for looplet numberWords = “Akshaykumar”, “Girishbhai”, “Patel”
for word in numberWords {
//Prints “Akshaykumar”
//Prints “Girishbhai”
//Prints “Patel”
numberWords.forEach { word in
} // same output as above
There is two ways of using For loop in swift, both are easy to use as well as very short for getting fast result.

Using the forEach loop is distinct from a for-in loop in two important ways:
You cannot use a break or continue statement to quit the current call of the bodyclosure or skip subsequent calls.

Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won’t skip subsequent calls.

String functions
String is a Collection of Characters. Not needing to always refer to the character’s collection makes using strings easier. For example, a Swift 4 String now has a direct count property that gives the character count:
let name = “AKSHAY”
name.count // 6
Swift now allows you to create a multi-line String literals. You wrap the strings in triple double quotes (“””String”””). You do not need to escape newlines and quotes within the string:
let intro = “””
Hello Everyone, I’m Mr.Akshaykumar Patel.

I’m an iOS developer.

You can use subscript syntax to access the Character at a particular String index.

let greeting = “Guten Tag!”
greetinggreeting.startIndex // G
greetinggreeting.index(before: greeting.endIndex) // !
greetinggreeting.index(after: greeting.startIndex) // u
let index = greeting.index(greeting.startIndex, offsetBy: 7); greetingindex // a
EquatableIn Swift 4, you could compare arrays, dictionaries and optionals as long as their elements were Equatable// Arrays of Intlet firstArray = 1, 2, 3
let secondArray = 1, 2, 3
let sameArray = firstArray == secondArray// Dictionaries with Int values
let firstDictionary = “Cosmin”: 10, “George”: 9
let secondDictionary = “Cosmin”: 10, “George”: 9
let sameDictionary = firstDictionary == secondDictionaryUsing the == operator to test equality in these examples worked since Int is Equatable in Swift 4. However, comparing collections of optionals was a common situation you might have run into with Swift 4 since optionals do not conform to Equatable.
Recursive constraints Swift 4 didn’t support defining recursive constraints on associated types in protocols:
protocol Phone {
associatedtype Version
associatedtype SmartPhone}
class IPhone: Phone {
typealias Version = String
typealias SmartPhone = IPhone
In this example, you defined a Smartphone associated type, but it might have proved useful to constrain it to Phone , since all smartphones are phones. This is now possible in Swift 4.1
protocol Phone {
associatedtype Version
associatedtype SmartPhone: Phone where SmartPhone.Version == Version, SmartPhone.SmartPhone == SmartPhone}
You use where to constrain both Version and Smartphone to be the same as the phone’s.

ClosuresClosures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

Closure expression syntax has the following general form:
{ (parameters) -; return type in
The parameters in closure expression syntax can be in-out parameters, but they can’t have a default value. Variadic parameters can be used if you name the variadic parameter. Tuples can also be used as parameter types and return types.The example below shows a closure expression version of the backward(_:_:) function from above:
Var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2 })
Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.

If you use these shorthand argument names within your closure expression, you can omit the closure’s argument list from its definition, and the number and type of the shorthand argument names will be inferred from the expected function type. The in keyword can also be omitted, because the closure expression is made up entirely of its body:
reversedNames = names.sorted(by: { $0 > $1 } )
Here, $0 and $1 refer to the closure’s first and second String arguments.

SubscriptsClasses, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as someArrayindex and elements in a Dictionary instance as someDictionarykey.

You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.

Here’s an example of a read-only subscript implementation, which defines a TimesTable structure to represent an n-times-table of integers:
struct TimesTable {
let multiplier: Int subscript(index: Int) -; Int {
return multiplier * index
let threeTimesTable = TimesTable(multiplier: 3)
print(“six times three is (threeTimesTable6)”)
// Prints “six times three is 18”
Error Handling
Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Some operations aren’t guaranteed to always complete execution or produce a useful output. Optionals are used to represent the absence of a value, but when an operation fails, it’s often useful to understand what caused the failure, so that your code can respond accordingly.

As an example, consider the task of reading and processing data from a file on disk. There are a number of ways this task can fail, including the file not existing at the specified path, the file not having read permissions, or the file not being encoded in a compatible format. Distinguishing among these different situations allows a program to resolve some errors and to communicate to the user any errors it can’t resolve.

Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated. For example, here’s how you might represent the error conditions of operating a vending machine inside a game:
enum VendingMachineError: Error {
case invalidSelection case insufficientFunds(coinsNeeded: Int)
case outOfStock}
Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error. For example, the following code throws an error to indicate that five additional coins are needed by the vending machine:
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.

Here is the general form of a do-catch statement:
do {
try expression
} catch pattern 1 {
} catch pattern 2 where condition {
} catch {
Type Casting
Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy.

Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type.

class MediaItem {
var name: String
init(name: String) {
self.name = name
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
let library =
Movie(name: “Casablanca”, director: “Michael Curtiz”),
Song(name: “Blue Suede Shoes”, artist: “Elvis Presley”),
Movie(name: “Citizen Kane”, director: “Orson Welles”),
Song(name: “The One And Only”, artist: “Chesney Hawkes”),
Song(name: “Never Gonna Give You Up”, artist: “Rick Astley”)

// the type of “library” is inferred to be MediaItem
Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

The example below defines two variables, movieCount and songCount, which count the number of Movie and Song instances in the library array:
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
print(“Media library contains (movieCount) movies and (songCount) songs”)
// Prints “Media library contains 2 movies and 3 songs”
This example iterates through all items in the library array. On each pass, the for-in loop sets the item constant to the next MediaItem in the array.

item is Movie returns true if the current MediaItem is a Movie instance and false if it is not. Similarly, item is Song checks whether the item is a Song instance. At the end of the for-in loop, the values of movieCount and songCount contain a count of how many MediaItem instances were found of each type.

Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

Here’s an example of using Any to work with a mix of different types, including function types and nonclass types. The example creates an array called things, which can store values of type Any:
var things = Any()
things.append((3.0, 5.0))
things.append(Movie(name: “Ghostbusters”, director: “Ivan Reitman”))
things.append({ (name: String) -; String in “Hello, (name)” })
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names). Extensions in Swift can:
Add computed instance properties and computed type properties
Define instance methods and type methods
Provide new initializers
Define subscripts
Define and use new nested types
Make an existing type conform to a protocol
Declare extensions with the extension keyword:
extension SomeType {
// new functionality to add to SomeType goes here
Extensions can add computed instance properties and computed type properties to existing types. This example adds five computed instance properties to Swift’s built-in Double type, to provide basic support for working with distance units:
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
let oneInch = 25.4.mm
print(“One inch is (oneInch) meters”)
// Prints “One inch is 0.0254 meters”
let threeFeet = 3.ftprint(“Three feet is (threeFeet) meters”)
// Prints “Three feet is 0.914399970739201 meters”
The repetitions(task:) method takes a single argument of type () -> Void, which indicates a function that has no parameters and does not return a value.

After defining this extension, you can call the repetitions(task:) method on any integer to perform a task that many number of times:
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
3.repetitions {
// Hello!
// Hello!
// Hello!
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of. You define protocols in a very similar way to classes, structures, and enumerations:
protocol SomeProtocol {
// protocol definition goes here
Protocols can require specific initializers to be implemented by conforming types. You write these initializers as part of the protocol’s definition in exactly the same way as for normal initializers, but without curly braces or an initializer body:
protocol SomeProtocol {
init(someParameter: Int)
Protocols can require specific instance methods and type methods to be implemented by conforming types. These methods are written as part of the protocol’s definition in exactly the same way as for normal instance and type methods, but without curly braces or a method body. Variadic parameters are allowed, subject to the same rules as for normal methods. Default values, however, can’t be specified for method parameters within a protocol’s definition.

As with type property requirements, you always prefix type method requirements with the static keyword when they’re defined in a protocol. This is true even though type method requirements are prefixed with the class or static keyword when implemented by a class:
protocol SomeProtocol {
static func someTypeMethod()
You can implement a protocol initializer requirement on a conforming class as either a designated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the required modifier:
class SomeClass: SomeProtocol {
required init(someParameter: Int) {
// initializer implementation goes here
The use of the required modifier ensures that you provide an explicit or inherited implementation of the initializer requirement on all subclasses of the conforming class, such that they also conform to the protocol.

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it. For example, Swift’s Array and Dictionary types are both generic collections. You can create an array that holds Int values, or an array that holds String values, or indeed an array for any other type that can be created in Swift. Similarly, you can create a dictionary to store values of any specified type, and there are no limitations on what that type can be.

Generic functions can work with any type. Here’s a generic version of the swapTwoInts(_:_:) function from above, called swapTwoValues(_:_:):
func swapTwoValues;T;(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA}
In addition to generic functions, Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary.

This section shows you how to write a generic collection type called Stack. A stack is an ordered set of values, similar to an array, but with a more restricted set of operations than Swift’s Array type. An array allows new items to be inserted and removed at any location in the array. A stack, however, allows new items to be appended only to the end of the collection (known as pushing a new value on to the stack). Similarly, a stack allows items to be removed only from the end of the collection (known as popping a value off the stack).

Automatic Reference Counting
Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.

However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you. This chapter describes those situations and shows how you enable ARC to manage all of your app’s memory. Using ARC in Swift is very similar to the approach described in Transitioning to ARC Release Notes for using ARC with Objective-C.

Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.

How ARC Works
Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.

However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.

Access Control
Access control restricts access to parts of your code from code in other source files and modules. This feature enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.

You can assign specific access levels to individual types (classes, structures, and enumerations), as well as to properties, methods, initializers, and subscripts belonging to those types. Protocols can be restricted to a certain context, as can global constants, variables, and functions.

In addition to offering various levels of access control, Swift reduces the need to specify explicit access control levels by providing default access levels for typical scenarios. Indeed, if you are writing a single-target app, you may not need to specify explicit access control levels at all.

Swift provides five different access levels for entities within your code. These access levels are relative to the source file in which an entity is defined, and also relative to the module that source file belongs to.

Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below.

Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.

Open access applies only to classes and class members, and it differs from public access as follows:
Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.

Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.

Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.

Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

Marking a class as open explicitly indicates that you’ve considered the impact of code from other modules using that class as a superclass, and that you’ve designed your class’s code accordingly.

Define the access level for an entity by placing one of the open, public, internal, fileprivate, or private modifiers before the entity’s introducer:
public class SomePublicClass {}
internal class SomeInternalClass {}
fileprivate class SomeFilePrivateClass {}
private class SomePrivateClass {}
public var somePublicVariable = 0
internal let someInternalConstant = 0
fileprivate func someFilePrivateFunction() {}
private func somePrivateFunction() {}
2.3 Advantages of Swift programming language
In 1980s, Objective-C was developed base on C programming language. Objective-C focuses mainly in object-oriented programming style which is the reason why Apple used it to develop iOS as well as MacOS applications. However, since 2014, Apple decided that Swift is the main programming language. There are various reasons why developers and Apple prefer Swift rather than Objective-C. Swift is developed by improving and revising the old and outdated Objective-C. Thus, Swift is more natural and user-friendly than Objective-C. Swift has the compiler named LLVM which reduces the files needed to generate a completed product without losing the flexibility. As mentioned in previous section, Swift has a runtime debugger which can work spontaneously with developers to track and alert all errors. As a result, Swift is easy to read, easy to maintain and user-friendly (Hillyer 2016, cited 22.02.2017)
Due to less amount of code and files, Swift can compile and build the program tremendously faster than Objective-C. Swift provides a side feature called Playground. Playground can be considered as a simulator which provides a test environment for developers to develop single module without building the entire program. Swift is developed within huge number of rebuilt libraries and frameworks which can provide supportive programming environment for developers (Solt 2015, cited 22.02.2017). IN short, Advandage of Swift Programming Language:
Error handling model and syntax improvements. ?
Swift is open source. ?
Swift is new programming language, combined with years of ?experience building Apple platforms.
Playgrounds make writing swift code very easy. ?
Swift was designed to be safe. ?
Swift is very fast. It uses Using high-performance LLVM compiler. ?
Interoperability with Objective-C. ?
2.4 MVC pattern for iOS development
The Model-View-Controller, best known for MVC (figure 7), design pattern is the fundamental for object-oriented programming. The MVC model is the combination of three crucial components, including model, view and controller (Apple 2015, cited 22.02.2017).

FIGURE 4 MVC design pattern (Apple 2014, cited 22.02.2017)
The model component can be considered as a database for application. Model is used to store the data as well as the logic provided by developer to control and process data storage. In Swift, model acts like a slave while the master acts like a controller. The model will process data and give response whenever there is a command from controller. Model can be a small built-in database from XCode or an outside database connected by controllers.
The view component refers to all the visual objects that contribute to user interface. Normally, view is used to display the data received from model and sends notifications regarding users’ actions. View acts like a slave from controller and a reflection from model.
The controller is the master of application. Controller acts as an intermediary between view and model. Controller will receive the notifications and input from view, analyze these notifications and transfer the command to model for processing. After receiving the response from model, controller will process the feedback and transfer to view as an update for specific objects. Controller can be considered as a waiter or waitress in a restaurant where model is the chef and view is the customer.
At a glance, Swift’s MVC (figure 5) pattern is the normal MVC pattern being used by many programming languages. However, the MVC pattern in iOS development has own strengths, such as dependency of view component or controller component. In iOS development, the view will, only, be controlled if developers decide to create a connection between view and controller. However, with the help of multiple controller classes provided by Apple, MVC design pattern in iOS development is well supported. The view component can be designed separately without writing the code or XML script. Besides, the MVC pattern from iOS development is adopting the flexibility of MVVM (Model-View-View-Model) to enhance its features by distribute equally tasks between model and controller.

FIGURE 5 iOS specific MVC pattern

CHAPTER 3 Evaluation of Swift
3.1 Speed
Apple has claimed that Swift makes apps run “lightning-fast”. During the Worldwide Developer Conference they showed two slides concerning the speed of Swift. The first slide showed a comparison between Python, Objective-C and Swift for performing a complex object sort. The graph showed that Objective-C was 2.8x as fast as Python, and Swift was 3.9x as fast as Python. This makes Swift approximately 1.4x faster than Objective- C for sorting complex objects. The second slide they showed compared Python, Objective-C, and Swift for RC4 encryption. This graph showed that Objective-C was 127x faster than Python, and Swift was 220x faster than python. This means that Swift 1.73x faster than Objective-C for RC4 encryption App14a.

While it is difficult to exactly reproduce any benchmarking results, I attempted to run these same benchmarking tests myself on my own computer. Since Apple did not specify what computer these benchmarks were run on, how the algorithms were implemented, or even what a complex object exactly is, much of the implementation was left up to my best guess. Additionally, any results achieved on my personal computer should be taken as approximate results at best, although they still should indicate general language efficiencies. I decided to expand my language comparison to include Python, Objective-C, Swift, Java, and C. While compiling Swift I used the first level of optimization by passing the compiler the “-O” flag. I did no compile optimizations for any of the other languages.
For the Java benchmarking I did not warm up the Java Virtual Machine, timing the algorithm only on the first run. Java will perform better after the JVM has been warmed up, but for approximate test this is sufficient. For the first test I wrote an algorithm in each language to sort a list of 1,000,000 objects in ascending order. The objects were sorted in order based on a randomly generated numerical instance variable that ranged from ?1000 to 1000. Since C does not support objects a struct was used instead. I ran each algorithm 25 times and plotted the results. Swift and Objective-C both performed approximately equal, running on average 1.4x faster than Python. How- ever both languages paled in comparison to Java and C, with Java being on average twice as fast as either language.

For the next test I decided not to implement RC4 encryption because of the difficulty of implementation. Instead I substituted another computationally complex algorithm, matrix multiplication. I multiplied two 500×500 matrices together with an O(n3) algorithm in each of the five languages, again running each algorithm 25 times in each language. In this test Swift far outperformed Objective-C by a significant margin, running on average almost 10x faster than python and 4x faster than Objective-C. While still not quite as fast as C, Swift’s performance was on par with Java.

FIGURE 6 Benchmarking Complex Object Sort
While these results are approximate they still show that it is unlikely that Swift is quite as fast as projected by Apple. It is possible that the performance document in the WWDC presentation could be achieved by Swift under special circumstances, but in the general case Swift is only moderately faster than Objective-C. Swift also needs to be compiled with optimizations in order to achieve anywhere close to reasonable performance. Without any optimizations swift performed worse than both Objective-C and Python in both algorithms. It is unclear exactly why Swift performs much better than Objective-C during matrix multiplication, but no better while sorting. I pre- dict that the difference in performance is partially because Objective-C does more work during runtime as a result of its dynamic method dispatch. Since swift mostly avoids dynamic dispatch it can execute significantly faster.

FIGURE 7 Benchmarking Matrix Multiplication
3.2 Feature Set
Swift’s creator, Christ Lattner, has said that Swift was heavily influenced by many other languages, and includes many of the features commonly found in other modern programming languages Lat14. While Swift has too many features to fully discuss in this thesis, many of the major language constructs are drawn from other languages. I went through each feature highlighted by Apple during the WWDS presentation and tried to identify the language that had a similar implementation. In general Swift includes almost all the common features found in a modern programming language, with only a few surprises. The first surprise is the heavy use of optional types. Inspired by the Haskell Maybe monad and optional types in Rust, Swift optionals allow the programmer to declare a variable that can be null App14b.
This feature helps to avoid null pointer references, and has been rarely seen in other widely used languages. The second surprise is that Swift uses Automatic Reference Counting (ARC) for memory management instead of a tracing garbage collector. Most modern languages, such as Java and Python, use a type of tracing garbage collector. While ARC is usually less efficient than tracing garbage collection, it can offer smoother performance and use less memory since it reclaims objects immediately App14b. Apple has decided that smooth performance and lower memory overhead is more important than overall efficiency. Additionally, Objective-C used reference counting, and it is likely that Apple saw no need to change this while creating Swift.
Swift Feature Languages with similar features
Closures JavaScript
Generics Java
Type Inference Haskell
Tuples Python
Functions as?First Class Objects JavaScript
Operator Overloading C++
Pattern Matching Scala, Haskell
Optional Types Haskell, Rust
Automatic Reference Counting Objective-C
Protocols Java, C++
Read-Eval-Print-Loop (REPL) Python
TABLE 1 Features highlighted in Apple’s WWDC presentation
Swift also has a few features that are noticeably missing. Swift offers no native support for exceptions such that there is no try/catch construct in the language. Instead Swift encourages the programmer to utilize optional types and enums to catch and handle errors without turning to exceptional control flow. Initially this feature was nautically missing, since unwrapping multiple optionals littered code with if-else blocks. The latest update to Swift now allows for unwrapping multiple optionals at once, which brings Swift closer to a traditional try/catch structure. Additionally, Swift offers no native support for concurrency or parallelism, instead relying on the Cocoa and Cocoa Touch framework for utilizing threads and processes. While workarounds exist to emulate both of these features, Swift deviates from other modern languages by not including them. It is possible that in future versions Swift will add support for exception handling and native concurrency support, but currently no such features exist.
3.3 Safety
Apple has strongly declared that Swift is a “safe” language. I understand this to mean that it is a type safe language, and that many errors can be caught at compile time, rather than producing unusual behavior at runtime. This idea of catching errors at compile time is prevalent throughout Swift, and manifests in several different ways. Swift attempts to get rid of null pointer errors by requiring all variables to be initialized either right away or during the init method of a class. If a variable either is not initialized immediately or could eventually be null than an optional type must be used. The optional type is defined as an enumeration with two cases, None and Some(T), which is very similar to the maybe monad from Haskell.
Swift offers a syntactic sugar for optionals, allowing the programmer to write ? after a variable type to demarcate it as an optional. If a variable is an optional type then it must be unwrapped before being used which saves the programmer from accidentally trying to access a null reference. However Swift also includes implicitly unwrapped optionals that are demarcated with the ! symbol after the variable type. These variables can be null but do not need to be unwrapped before being used, acting as a normal variable. If an implicitly unwrapped optional is null and the programmer tries to access it a run-time error will occur. These types undermine the safety of optional types since a programmer using implicitly unwrapped variables still runs into null pointer errors.
Swift emphasizes explicitly declaring possible dangerous code fragments. Possibly null variables must be marked as optionals, and any subclass that overrides a method must be explicitly marked. Additionally, any variables in a closure must be prefixed with self, to disambiguate between variables in the closure and those in an outer scope. While these do not help the compiler, they do inform the programmer exactly what they are doing, making accidentally accessing the wrong method or variable much less likely. Swift also has clear rules about when variables are copied or passed by reference. All classes are passed via reference, and all structs and enums are copied. Method parameters cannot be modified within a method unless they are explicitly declared to be inout in the method declaration. While some of these constraints can be occasionally difficult to work with, overall they help the programmer understand clearly when they are dealing with potentially dangerous areas of code.

2.1 iOS Game Development Platform Introduction
iOS has become a great platform for developers to develop games 3. In WWDC 2013, Apple finally understood the significance of games for their platforms and announced Sprite Kit followed by Scene Kit and Metal in coming. iOS games are better every year with the advancements in game development frameworks. iOS 9 provides powerful gaming technologies to build better quality games.
2.2 iOS Game Development History
In early days, game developers used OpenGL API to make 2D and 3D graphics on the screen 4. Foundation and CocoaTouch was on the upper level to manipulate UIKit objects. The development features like Sprite, partical emitters, maps, bounding boxes requires lower level structuring. In 2011, Apple introduced GLKit framework to reduces the effort provided by earlier version of OpenGL. Third-party frameworks, such as Unity, GameMaker, Unreal Engine, Cocos2D also made the game development easier for the developers by keeping the design aspect of the game more focus. Since none of these third-framework were supported by Apple, there would be integration problem with new version of iOS. Finally, Apple introduced SpriteKit framework for making 2D games in 2013.
2.3 Comparing with Other Platform
iOS Games can be made in other third party platform engines like Unity, Unreal, Cocos2D and so on. Third party platform engines are especially popular among the indie developers. Third party platforms are closed source and mostly cost money for full version.
Before the launch of SpriteKit, Cocos2D was a popular third party framework for creating iOS games. Being Apple’s native game development engine for iOS platform, SpriteKit has emerged as a serious challenger to Cocos2D. Gaming Platforms are compared in Table 1.
Platform Pros Cons
SpriteKit Cocos2D Unity2D
Native framewrok, supported by Apple Perfect fo casual games ? Cross platform
Built in to XcodeFree and open source strong community of
Easier for beginners Hardware accelerated asset and plugin creators
New framework, still more upgrades to come. graphics and good performance Need to pay for full licence.
No large commercial entity support and bug fixes Collaboration is difficult
APIs are somewhat unorthodox Performance is not great
The engine source code is not available.
TABLE 3 Comparing SpriteKit, Cocos2D and Unity2D
2.4 Comparing with Other Platform
Apple provides three game development frameworks to make games for iOS platform 7. They are SpriteKit, SceneKit and Metal. iOS games are better than ever with the latest advancements in Sprite Kit, Scene Kit and Metal. iOS 9 provides more powerful and easy to use gaming technologies like GameplayKit, ReplayKit, and Model I/O. Table 2 shows the differences between SpriteKit, SceneKit and Metal.
Sprite Kit Scene Kit Metal
Designed for 2D games
Focus on simplicity and automation ?
Fast to learn ?
Can show 3D ?objects from scenekit ? Create 3D Games
Similar style to spritekit?
Requires higher resources?
A great next step from spritekit Full control over the GPU to do whatever you can imagine
Not a beginner friendly
Making games takes a lot longer?
Possibly less resources available
TABLE 2. Differences between SpriteKit, SceneKit and Metal.

SpriteKit is the best framework to start learning and developing games. After SpriteKit, we can surely start developing games with SceneKit and Metal in future.
CHAPTER 4 introduction to sprite kit framework
4.1 Description
Sprite Kit is a framework for developing 2D games for iOS devices. It is easy to learn, powerful and fully supported by Apple, which makes it more reliable to use than third-party game development engines. As Sprite Kit is a native framework of iOS, it has an in-build support for using the particle effects, texture effects, and physics simulations. The performance of Sprite Kit is better than, that of other third-party frameworks or engines.
4.2 Elements of SpriteKit SpriteKit game consists of many scenes which are made of nodes, and the functioning of nodes in a scene is determined by actions.
A scene is basically a collection of different elements such as sprites, sounds, and so on, in a logical way. Suppose we want to make a menu, we’ll have to put some buttons, background, and sounds in a manner that is positioned according to our needs.A Sceneobject is a collection of nodes, but a scene itself acts as a node. Imagine a tree of nodes having scene objects as its root. As all nodes in the scene are positioned in defined coordinates. This linkage of a node with its descendant(s) is very useful. Say, if you rotate a node on the top of the tree, allthe nodes will be subsequently rotated. A level in a game is called as a Scene. It holds all the contents, i.e. nodes and sprites that are to be rendered. A scene in Sprite Kit is represented by SKScene objects. In technical terms, Scene is an SKSceneobject, which holds an SKNodeobject (such as SKSpriteNode objects for sprites) inside a view (SKView object), so that we can render and use them. Scene is itself an SKNodeobject, which acts as a root node and attaches in an SKViewobject. Other objects required for that scene are added to this node as a child node. A scene runs different kinds of actions and simulates physics (if required), and then renders the node tree. A game consists of many scenes, and we can make as many scenes required by sub-classing SKScene class. An SKView object is required to display a scene.

When we create a scene, we can define many of its properties such as size, origin, and so on. as we require in our game. A scene size defines the visible area in the SKView object. Of course, we can put nodes outside this area, but they will be totally ignored by the renderer. However, if we try to change the position property of a scene, it will be ignored by Sprite Kit because a scene is a root node in a node tree, its default value isCGPointZero. But we can move scene origin by the anchorPointproperty.
Default value for anchorPointis (0.5,0.5), which indicates the center point of the screen.By reassigning a new anchorPointproperty, we can change the coordinate system for its child. For example, if we set anchorPoint to (0,0), the child node of the scene will start from the bottom left of the scene.If we make the anchorPoint (0.5, 0.5) or the middle of the screen, the child node of the scene will start from the middle of the screen. It totally depends on us and what anchorPointwe choose as per our requirement.

The basic building blocks for all the content in a scene is called Node. The SKNode acts like a blueprint for all other nodes. The SKNode have attributes like position, rotation, scale and alpha. The Figure 2 shows the properties of SKNode and the link with other nodes.

FIGURE 8 SKNode properties.

The SKNode class does not draw anything on a scene by itself, but applies its properties to its descendants. There are node subclasses as follows:
SKSpriteNode: This can be used for drawing textured sprites and playing video content. ?
SK3DNode: This can be used for rendering a SceneKit scene as a 2D textured image. ?
SKVideoNode: This can be used for playing video content. ?
SKLabelNode: This can be used for rendering a text string. ?
SKShapeNode: This can be used for rendering a shape, based on a ?core graphics path. ?
SKEmitterNode: This can be used for creating and rendering ?particles. ?
SKCropNode: This can be used for cropping child nodes using a ?mask.

SKEffectNode: This can be used for applying a core image filter to its ?child node. ?
SKLightNode: This can be used for applying lighting and shadows to ?a scene. ?
SKFieldNode: This can be used for applying physics effects to a specific portion of the scene.?
Coordinate system
Everything in a game built in Sprite Kit is related to nodes, and it follows a node treestructure where a scene is a root node and other nodes are child nodes of it. When we put a node in the node tree, it uses its position property to place it within the coordinate system provided by its parent.As a scene is also a node, it is placed inside the view provided by the SKViewobject. The code part which we deleted in viewDidLoad, GameScene, was added as a child in the SKViewobject. A scene uses its parent SKViewobject coordination systemto render itself and the content within it. The coordinate system is the same as we learned in basic mathematics.

As the preceding diagram shows, if we move right from (0,0), then x will be positive, and negative if we move left from (0,0). If we move up from (0,0), then y will be positive, and negative if we move down from (0,0). Coordinate values are measured in points and when the scene is rendered, it will be converted to pixels.All the nodes in Sprite Kit will not draw the content.
For example, SKSpriteNodeis used to draw sprites in a game, but SKNodeclass does not draw anything as SKNode is a fundamental building block for most Sprite Kit content
In SpriteKit, Action is used to animate scenes. An action is an object which is used to change the structure of the node in the scene. All actions are implemented by the SKAction class. The most common things that an action can do are as follows:
Changing a node’s position and orientation. ?
Changing a node’s size or scaling properties. ?
Changing a node’s visibility or making it translucent. ?
Changing a sprite node’s contents so that it animates through ?a series of textures. ?
Colorizing a sprite node. ?
Playing simple sounds. ?
Removing a node from the node tree. ?
Calling a block. ?
Invoking a selector on an object. ?
4.3 Features of Sprite Kit ?SpriteKit provides many features to facilitate the development of a game. These features can be used for enhancing the experience as well as the performance of the game. ?
Particle Emitter Editor ?
Particle emitters are used to create special effects like rain, fire, snow that change over the time 14. Emitters controls the position and motion of the particle. The following emitter items can be controlled in SpriteKit: ?
The location and duration of the particle. ?
The amount of particles. ?
The size and color of the particle, throughout its lifetime. ?
The direction and rotation of the particle from its origin point. ?
Shaders are used to produce a variety of special effects. They calculate rendering effects on a graphic hardware with a high degree of flexibility. In Sprite Kit, shaders are represented by the SKShaderNode class object.
Lighting and Shadows
Lighting and shaders effects are produced using the SKLightNode class object. The SKLightNode object can:
spread a lighting effect at any desirable position on the scene ?
add lightning in any sprite ?
support colors and shadows ?
Simulating Physics
In order to imitate the physics, we need to add physics bodies to the scenes 18. A physics body property uses the SKPhysicsBody class object. In the life cycle of the frame, the didSimulatePhysics function is called just after actions are evaluated. The work of this function is to calculate the physical properties, such as gravity, velocity, friction, restitution, collision. There are three kinds of physics bodies. They are Dynamic, Static and Edge.
Dynamic Volume Static Volume Edge
Physical objects with volume and mass which can be affected by forces and collisions. It is unaffected by forces or collisions. It is a static volume-less body.

It is used to move and collide physics bodies.

It can be used to take up space in the scene.

It can be used to represent the boundries in the scene.

TABLE 2 Differences between physics bodies.

Moreover, you can shows(Figure 10) the standard shapes provided by SpriteKit.

FIGURE 10 Volume-based and Edge-based physics bodies
The Game Loop
The game loop is a important part of every game. The game loop allows the game to run efficiently. Figure 11 shows the rendering loop, which is used by SpriteKit.
The following game loop steps are explained in SpriteKit Programming Guide provided by Apple:
The update function is the place to implement in game simulation like running nodes, input handling, artificial intelligence, game scripting, and other game logic. ?
The scene processes actions on all the nodes in the tree. It finds all running actions and applies those changes to the tree.

The scene’s didEvaluateActions method is called after all actions for the frame have been processed.?
The scene simulates physics on nodes in the tree that have physics bodies. ?

FIGURE 11 The Game Loop
The scene’s didSimulatePhysics method is called after all physics for the frame has been simulated.
The scene applies any contraints associated with nodes in the scene. Contraints are used to establish relationships in the scene. ?
The scene calls its didApplyConstraints method. ?
The scene calls its didFinishUpdate method. This is the last chance to make changes to the scene.
Finally, SKViewrenders the scene.The frame is complete and it continues 60 times per second.

Overall Swift is a major improvement from Objective-C and a great step in the right direction for Apple. Although unlikely to be as fast as projected in most use cases, the lack of dynamic dispatch and strictness of the type system allow Swift to see significant speed improvements. Swift will never be as fast as Java or C, but for a language that feels closer to a scripting language than a systems language the efficiency is welcome if not overly impressive. Swift should be easy for most developers to learn since it has very similar syntax to Java or Scala. Most of the features found in Java, Scala, or Python are also present in Swift, and the only features that Swift lacks have little impact on the overall usefulness of the language. The only disappointment I had about Swift is that it does not have anything new or unique. Apple has created a language that feels extremely similar to the languages that are already being used today. There are a few details that are unique or original, including external parameter names, computer properties, and native variable listeners. Other than these few details Swift does not advance the field of programming languages or push developers to learn a new way of programming.
While Swift may not have many original features, it does have a focus on making sure the features that it does have are implemented correctly and intelligently. There is a major focus on eliminating programmer and runtime errors by having the compiler catch every possible sources of error. Often times the level of safety is left up to the programer such as the use of immutability and optionality. Other times Swift forces the programmer to conform to its own rules, such as when using protocols or closures. While this can sometimes be frustrating to work with, Swift significantly decreases number of errors the result from programmer mistakes. These bugs can often be hard to track down, such as when a variable or method is unknowingly modified, and Swift helps the programmer catch them before runtime. While building SwiftDraw I was pleased with the safety of Swift the vast majority of the time. However I spent a significant amount of time wrestling with the strictness of the compiler and the strange behavior that arises when working with Objective-C code and the Cocoa Touch framework. This seems to be the weakest area of Swift, and unfortunately occurs frequently while writing iOS apps. Hopefully this area becomes easy to deal with as the language matures and develops.
I believe that more and more developers will switch to using Swift over Objective-C. The learning curve is small and Swift offers many advantages in terms of syntax and guaranteeing program correctness. While Objective- C may never go away, Swift will soon become the default language for all iOS and Mac OS X applications. The language still has a few rough areas but the language will continue to improve and develop until most of the major flaws are fixed. Swift is a major step forward for Apple and should be a success for both the company and its developers.

Apple Inc. (2014). Core OS Layer. Available at: https://developer.apple.com/library/content/documentation/Miscellaneous/Conceptual/iPhoneOST echOverview/CoreOSLayer/CoreOSLayer.html#//apple_ref/doc/uid/TP40007898-CH11-SW1. Cited 22.02.2017.
Apple Inc. (2015). Model-View-Controller. Available at: https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia- CocoaCore/MVC.html. Cite 25.02.2017.
Apple Inc. (2017). About Swift. Available at: https://swift.org/about/#swiftorg-and-open-source. Cite 22.02.2017.
Apple Inc. (2017). Xcode 8. Available at: https://developer.apple.com/xcode/. Cite 22.02.2017.
Inc. Apple. Apple wwdc 2014 – swift introduction. https://www.youtube.com/watch?v=MO7Ta0DvEWA, June 2014.
Inc. Apple. The Swift Programming Language. 1. Apple, Inc., 2014.
Inc. Apple. Using Swift with Cocoa and Objective-C. 2. Apple, Inc., 2014.
iOSGameDevelopmentEssentials.ByChuckGaffney.Dateofretrieval 4.4.2016 https://books.google.fi/books?id=AvWoCwAAQBAJ&pg=PA64&lpg=PA64&dq=ios+game+development+history&source=bl&ots=PqWbWT90vV&sig=4GmPzu4DPfeamn19DcUyJgkxHno&hl=en&sa=X&redir_esc=y#v=o nepage&q=ios%20game%20development%20history&f=false ?
Cocos2DVSSpriteKitvsUnity2D.Dateofretrieval5.4.2016 https://www.raywenderlich.com/67585/cocos2d-vs-sprite-kit-vs-unity-2d-tech-talk-video ?
SpriteKit. https://developer.apple.com/spritekit/ ?
Building Your Scene. Date of retrieval 9.4.2016https://developer.apple.com/library/ios/documentation/GraphicsAnimation /Conceptual/SpriteKit_PG/Nodes/Nodes