Você está na página 1de 15

Swift Programming

Chapter 1 : Introduction
1.1) Introduction to Swift language :
Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or
anything else that runs code. It’s a safe, fast, and interactive programming language that
combines the best in modern language thinking with wisdom from the wider Apple engineering
culture and the diverse contributions from its open-source community. The compiler is optimized
for performance and the language is optimized for development, without compromising on
either.

Swift is friendly to new programmers. It’s an industrial-quality programming language that’s


as expressive and enjoyable as a scripting language. Writing Swift code in a playground lets you
experiment with code and see the results immediately, without the overhead of building and
running an app.

Swift defines away large classes of common programming errors by adopting modern
programming patterns:

 Variables are always initialized before use.


 Array indices are checked for out-of-bounds errors.
 Integers are checked for overflow.
 Optionals ensure that nil values are handled explicitly.
 Memory is managed automatically.
 Error handling allows controlled recovery from unexpected failures.

1.2) Features to Swift language :

 Open Source –
Swift 4 was developed in the open at Swift.org, with source code, a bug tracker,
mailing lists, and regular development builds available for everyone. This broad
community of developers, both inside Apple as well as hundreds of outside
contributors, work together to make Swift even more amazing. Swift already supports
all Apple platforms as well as Linux, with community members actively working to
port to even more platforms.
 Modern –
Swift is the result of the latest research on programming languages, combined with
decades of experience building Apple platforms. Named parameters brought forward
from Objective-C are expressed in a clean syntax that makes APIs in Swift even
easier to read and maintain. Inferred types make code cleaner and less prone to
mistakes, while modules eliminate headers and provide namespaces. Memory is

Government Polytechnic, Kolhapur Page 1


Swift Programming

managed automatically, and you don’t even need to type semi-colons. These forward-
thinking concepts result in a language that is easy and fun to use.

 Fast and Powerful –


From its earliest conception, Swift was built to be fast. Using the incredibly high-
performance LLVM compiler, Swift code is transformed into optimized native code
that gets the most out of modern hardware. The syntax and standard library have also
been tuned to make the most obvious way to write your code also perform the best.

 Other features –
1. Closures unified with function pointers
2. Tuples and multiple return values
3. Generics
4. Fast and concise iteration over a range or collection
5. Structs that support methods, extensions, and protocols
6. Functional programming patterns, e.g., map and filter
7. Native error handling using try / catch / throw

1.3) Need of Swift language –

Programming can be stressful, especially if you try to start out with an archaic
language. Newbies are better off dipping toes in something a bit more modern, such as
Python, Ruby, or Swift. But coding veterans also have much to gain by switching to
Swift, including those who feel burned out on mainstream languages.

 Swift is open source –


Apple’s decision to make Swift open source has accelerated adoption and
development of the language. Swift became one of the top 10 most popular
programming languages in the world, according to the monthly TIOBE index in
March 2017. It’s also among the ten 10 languages as assessed by the PYPL
Popularity of Programming Languages tracker.

 Swift is easy to learn –


Apple built its language to be easy to use and with syntactic simplicity to match
Python. What this means is you can begin actually building your apps much faster
than you would be able to when learning any other dev platform. Some say that in
just 3-4 months, you’ll be able to make real app ideas happen.

 Swift is fast –
People claim code created using Swift is as fast as compiled C code. The language
has been developed in such a way as to dispense with tedious tasks, such as entering
semi-colons in line breaks in favor of a more responsive development environment.
Apple claims search algorithms complete up to 2.6 times faster than Objective-C and
up to 8.4 times faster than Python 2.7.

Government Polytechnic, Kolhapur Page 2


Swift Programming

 Swift is safe –
The Swift team is quite focused on security. That is why when you work with the
language, you shouldn’t come across any unsafe code and will use modern
programming conventions to help keep watertight security in your apps.

1.4) History –

Development of Swift started in July 2010 by Chris Lattner, with the eventual
collaboration of many other programmers at Apple. Swift took language ideas "from
Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list". On
June 2, 2014, the Apple Worldwide Developers Conference (WWDC) application
became the first publicly released app written with Swift. A beta version of the
programming language was released to registered Apple developers at the conference, but
the company did not promise that the final version of Swift would be source code
compatible with the test version. Apple planned to make source code converters available
if needed for the full release.

Swift reached the 1.0 milestone on September 9, 2014, with the Gold Master of Xcode
6.0 for iOS.Swift 1.1 was released on October 22, 2014, alongside the launch of Xcode
6.1.Swift 1.2 was released on April 8, 2015, along with Xcode 6.3.Swift 2.0 was
announced at WWDC 2015, and was made available for publishing apps in the App Store
in September 21, 2015. Swift 3.0 was released on September 13, 2016.Swift 4.0 was
released on September 19, 2017.Swift 4.1 was released on March 29, 2018.

Swift won first place for Most Loved Programming Language in the Stack Overflow
Developer Survey 2015 and second place in 2016.

Government Polytechnic, Kolhapur Page 3


Swift Programming

Chapter 2 : Basic Working


2.1) Variables and constants–

Constants and variables associate a name (such as maximum Number Of Login


Attempts or welcome Message) with a value of a particular type (such as the number 10
or the string "Hello"). The value of a constant can’t be changed once it’s set, whereas a
variable can be set to a different value in the future.
In this example, the maximum number of allowed login attempts is declared as a
constant, because the maximum value never changes. The current login attempt counter is
declared as a variable, because this value must be incremented after each failed login
attempt.

Declaring Constants and Variables –

The syntax for declaring and initializing, as shown in the previous example, is as follows:

1. var is the keyword that indicates a new variable declaration.


2. age is the name of the variable.
3. : separates the variable name and type.
4. Int is the type of the variable.
5. = is used to assign a value to the variable.
6. 42 is the value of the variable.

2.2) Basic operators –


An operator is a special symbol or phrase that you use to check, change, or combine
values. For example, the addition operator (+) adds two numbers, as in let i = 1 + 2, and
the logical AND operator (&&) combines two Boolean values, as in

Government Polytechnic, Kolhapur Page 4


Swift Programming

Swift supports most standard C operators and improves several capabilities to eliminate
common coding errors. The assignment operator (=) doesn’t return a value, to prevent it
from being mistakenly used when the equal to operator (==) is intended. Arithmetic
operators (+, -, *, /, % and so forth) detect and disallow value overflow, to avoid
unexpected results when working with numbers that become larger or smaller than the
allowed value range of the type that stores them. You can opt in to value overflow
behavior by using Swift’s overflow operators, as described in Overflow Operators.

Terminology-

Operators are unary, binary, or ternary:

 Unary operators operate on a single target (such as -a). Unary prefix operators
appear immediately before their target (such as !b), and unary postfix operators
appear immediately after their target (such as c!).
 Binary operators operate on two targets (such as 2 + 3) and are infix because they
appear in between their two targets.
 Ternary operators operate on three targets. Like C, Swift has only one ternary
operator, the ternary conditional operator (a ? b : c).

Arithmetic Operators + - * / %

Logical Operators && || !

Comparison Operators == < > <= >= !=

Bitwise Operators | & ! ^ ~

Assignment Operators = += -= *= /=

Range Operators a…b a..<b …a …b

Table 2.1 Operators in Swift.

Government Polytechnic, Kolhapur Page 5


Swift Programming

2.3) Functions –
Functions are self-contained chunks of code that perform a specific task. You give a
function a name that identifies what it does, and this name is used to “call” the function to
perform its task when needed.

Swift’s unified function syntax is flexible enough to express anything from a simple C-
style function with no parameter names to a complex Objective-C-style method with
names and argument labels for each parameter. Parameters can provide default values to
simplify function calls and can be passed as in-out parameters, which modify a passed
variable once the function has completed its execution.

Defining and Calling Functions –

When you define a function, you can optionally define one or more named, typed
values that the function takes as input, known as parameters. You can also optionally
define a type of value that the function will pass back as output when it is done, known as
its return type.

Every function has a function name, which describes the task that the function
performs. To use a function, you “call” that function with its name and pass it input
values (known as arguments) that match the types of the function’s parameters. A
function’s arguments must always be provided in the same order as the function’s
parameter list.

Syntax –

func function_name (Parameters) -> return_type


{
Statement1
Statement2
---
Statement N
return parameters
}

Example –

func student(name: String) -> String {


return name
}
print(student(name: "First Program"))

Government Polytechnic, Kolhapur Page 6


Swift Programming

2.4)Loops –
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple


times. Following is the general from of a loop statement in most of the programming
languages −

1.While Loop –

A while loop starts by evaluating a single condition. If the condition is true, a set of
statements is repeated until the condition becomes false.

Here’s the general form of a while loop:

while condition
{
statements
}

Figure 2.1. While Loop

Government Polytechnic, Kolhapur Page 7


Swift Programming

2.For Loop –

You use the for-in loop to iterate over a sequence, such as items in an array, ranges of
numbers, or characters in a string.

Syntax –
for index in var
{
statement(s)
}

Example –
var someInts:[Int] = [10, 20, 30]

for index in someInts


{
print( "Value of index is \(index)")
}

Figure 2.2. For Loop

Government Polytechnic, Kolhapur Page 8


Swift Programming

3.Repeat-While Loop –

The other variation of the while loop, known as the repeat-while loop, performs a single
pass through the loop block first, before considering the loop’s condition. It then
continues to repeat the loop until the condition is false.

Syntax –
Repeat
{
statements

} while condition

Example –
var index = 10
repeat
{
print( "Value of index is \(index)")
index = index + 1

} while index < 20

Figure 2.3. Repeat-while Loop

Government Polytechnic, Kolhapur Page 9


Swift Programming

Chapter 3 : Special Functions


3.1)Extensions –
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

Syntax -
Extension SomeType
{
// new functionality can be added here
}

Existing type can also be added with extensions to make it as a protocol standard and its
syntax is similar to that of classes or structures.

Extension SomeType: SomeProtocol, AnotherProtocol


{
// protocol requirements is described here
}

If you define an extension to add new functionality to an existing type, the new
functionality will be available on all existing instances of that type, even if they were
created before the extension was defined.

Government Polytechnic, Kolhapur Page 10


Swift Programming

3.2)Tuples –
Swift 4 also introduces Tuples type, which are used to group multiple values in a single
compound Value. The values in a tuple can be of any type, and do not need to be of same
type.

For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type,
and other is integer type. It is a legal command .let Implementation Error = (501, "Not
implemented") is an error when something on the server is not implemented, It returns
two values. Error Code, and Description.

You can create tuples from as many values as you want and from any number of
different data types.

Syntax of Tuple declaration −

Var Tuple_Name = (Value1, value2,… any number of values)

Tuple declaration −

var error501 = (501, “Not implemented”)

You can access the values of tuple using the index numbers that start from 0.

Example of accessing tuple Values −

print(“The code is\(error501.0)”)


print(“The definition of error is\(error501.1)”)

You can name the variables of a tuple while declaring , and you can call them using their
names

var error501 = (errorCode: 501, description: “Not Implemented”)


print(error501.errorCode) // prints 501.

Tuples are helpful in returning multiple values from a function. Like, a web application
might return a tuple of type ("String", Int) to show whether the loading was successful or
failed.By returning different values in a tuple we can make decisions depending on
different tuple types.

Note − Tuples are useful for temporary values and are not suited for complex data.

Government Polytechnic, Kolhapur Page 11


Swift Programming

3.3)Protocols –
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.

Syntax –

protocol SomeProtocol
{
// protocol definition goes here
}

Custom types state that they adopt a particular protocol by placing the protocol’s name
after the type’s name, separated by a colon, as part of their definition. Multiple protocols
can be listed, and are separated by commas:

struct SomeStructure: FirstProtocol, AnotherProtocol


{
// structure definition goes here
}

If a class has a superclass, list the superclass name before any protocols it adopts,
followed by a comma:

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol


{
// class definition goes here
}
A protocol can require any conforming type to provide an instance property or type
property with a particular name and type. The protocol doesn’t specify whether the
property should be a stored property or a computed property—it only specifies the
required property name and type. The protocol also specifies whether each property must
be gettable or gettable and settable.

protocol SomeProtocol
{
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: Int { get }
}

Government Polytechnic, Kolhapur Page 12


Swift Programming

Chapter 3 : Applications
3.1)Applications os swift –
Swift was developed by apple and is open-source it is mainly used for developing
application and software, Swift is now open source so it is growing fastly. Many
companies are adopting swift as their main programming language. At present swift is in
development phase so same companies are using swift.

1. MAC OS.
2. IOS .
3. Watch OS.

Mobile Development-

Swift is a general-purpose programming language developed by Apple Inc. for iOS,


OS X, watchOS and tvOS. Currently it is the most popular open source programming
language on Github.

1. Firefox .
2. Youtube.
3. Wordpress.

3.1)Future scope –
Swift is fairly a very new language but it have gained popularity very quickly and is
also open source. Developers are loving it after Swift 2.0 release. And most likely if it
goes with same speed in near future iOS development will be totally moved to Swift and
support for Objective-C will be removed.

More over Google, Facebook and Uber are considering Swift as their main language
for production. So Swift is not only being considered for iOS Apps only

Government Polytechnic, Kolhapur Page 13


Swift Programming

Conclusion

• By the above description we can understand the need of Swift Language in future,
so swift IDE will be the best future for application development. Now a days swift
is in development phase for the server side scripting, so in future it will be used for
server either of cloud.

• This technology has bright future scope because day by day need of data would
increase and security issues also the major point. In now days Facebook and
Google is taking swift as main language.

• So major companies like Firefox, Word press, YouTube etc. are adopting swift
for IOS app development and in future there can be many names in the list.

Government Polytechnic, Kolhapur Page 14


Swift Programming

References

https://www.quora.com/What-is-the-future-of-Swift

https://developer.apple.com/swift/

https://www.tutorialspoint.com/swift/swift_protocols.htm

https://www.quora.com/What-is-the-use-of-Swift-language

https://en.wikipedia.org/wiki/Swift_(programming_language)

Government Polytechnic, Kolhapur Page 15

Você também pode gostar