0% found this document useful (0 votes)
2 views28 pages

Week01B DataTypes-Input-Output Control Loops

Uploaded by

dhwanirv2404
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Week01B DataTypes-Input-Output Control Loops

Uploaded by

dhwanirv2404
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Introduction to Swift Programming

u First Swift Program: Printing a line of Text - using playground or swift project
u Data Types, Constants and Variables
u Type Inference
u Strings and strings Interpolation
u Adding integer values
u Arithmetic – Arithmetic Overflow Checking and Operator Precedence
u Decision Making : The if conditional statement and switch.. Case
u Loops – for repetitive tasks
u Optionals – A type that can contain nil if no value provided.

Prepared by Sujeet Lohan


2
Introduction to Swift Programming

u A First Swift Program: Printing a line of Text


print(“ Welcome to Swift Programming”); // use of print function, part of Standard
Swift Library

Note: Swift does not have a main function or method. In Xcode project, file that contains the entry point
for a Swift project must be named – [Link] ( extension - .swift )
Any globally spaced statements in [Link] – that is statements that are not written inside a function,
method or type definitions serve as app’s entry point.
u Commenting your code – Comments in code are ignored by compiler
// -- single line comment
/* your multi-line comments
here … */
Prepared by Sujeet Lohan
3
Introduction to Swift Programming

u Function print displays a line of text to the standard output


u It is a Swift Standard Library function.
u Where standard output appears depends on the type of program and where you
execute it.
u If you execute print in the playground, the result displays in playground’s editor window
u If you execute any app from a XCode project, output appears in the Debug area at the bottom of the
XCode window.
u If you execute an macOS app outside of XCode, the result is sent to a log file that you can view in the
console app
u If you execute an iOS app on a device, the result is sent to a log file that you can view in Xcode’s
Devices window

Prepared by Sujeet Lohan


4
Introduction to Swift Programming

u Escape Sequences – special characters


u \n ( new line) , \t ( tab), \\ ( backslash, \r ( carriage return, \” (double quotes), \’ (single quote), \0
(null character), \u{n} (Unicode character, n is between one and 15 hexadecimal digits)
u Semicolons are not required in Swift, but if you place more than one statement on the same line,
they must be separated by semicolon
u Executing the Application/Project
u If it is playground, it executes immediately when you load it.
u If it is a Xcode project ( .swift file ), then you see output in Debug window
u Compilation and syntax errors
u As you write your code in a playground or in a .swift file that is part of Xcode project, the compiler
continuously compiles your code.
u Any compilation errors are indicated by stop-sign-shape symbol displayed to the left of lines of the code
in which error occurs.
Prepared by Sujeet Lohan
5
Types, Constants and Variables

u Data Types
u Integers – denoted by keyword - Int
u Examples:
var number1 = 14; // var keyword indicates a variable. Makes use of type inference

var student_id = 1001; // var keyword indicates a variable. Makes use of type inference
var account: Int = 1234; // var keyword indicates a variable. Here type is Integer.
print( number1);
print(student_id );
print(account );
print( 10 + 20); print( 30 – 5); print( 5 * 6); // If you are writing them in the same line.

Prepared by Sujeet Lohan


6
Types, Constants and Variables

u Types
u Integers – denoted by keyword - Int
u Various Integers Types:
Int : Default – 4 bytes or 8 bytes Int8: 8 bits ( I byte)
Int16: 16 bits ( 2 bytes) Int32: 32 bits ( 4 bytes)
Each type’s minimum and maximum values can be determined with its min and max properties.
For examples: [Link] and [Link] for type Int.
print(“ The maximum Int value is \([Link])”)
print(“ The maximum Int value is \([Link])”)

Prepared by Sujeet Lohan


7
Types, Constants and Variables

u Floating-point Data Types ( conforms to IEEE 754)


u Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal
points. For example, 3.14, 0.1, and -23.15.
var salary: Float = 1234.40
var grades:Float
print(salary )
u Double − This is used to represent a 64-bit floating-point number and used when floating-point
values must be very large. For example, 3.14159, 0.1, and -273.158.
var balance: Double = 234.567
var totalSales = 23456.45 // It is implicitly double
print(balance)
Prepared by Sujeet Lohan
8
Types, Constants and Variables

u String Data Type


u String − This is an ordered collection of characters. For example, "Hello, World!“

var courseName = “Swift”


var campusName: String = “Davis”
var description = “This course is about Swift Programming”

Prepared by Sujeet Lohan


9
Types, Constants and Variables
u Character − This is a single-character string literal. For example, "C“
let exclamationMark: Character = "!” // let makes it constant
u Boolean − This represents a variable that can hold true or false value. Keyword - Bool
var mallOpen: Bool = true
var hasPostOffice: Bool = false
u Optional − This represents a variable that can hold either a value or can have no value (nil)
var courseName:String // Here type is String
print(courseName) // It will give you an error. Variable must be initialized
var courseName:String? // String followed by question mark will make it a String Optional
print(courseName) // It will give you nil. No compilation error
courseName = “Mobile”
print(courseName) // It will print – optional(“Mobile”)
print(courseName!) // It will print – Mobile. With “!” , it is unwrapped. It is called unwrapping
Prepared by Sujeet Lohan
10
Constants – use keyword let

Examples:
let name = “iOS Programming”
let SIN: Int = 100
let pi: Float = 3.14
--------------------------------
let numberOfCampuses = 4
numberOfCampuses += 2

Note: Here compiler will issue an error because constants won’t vary.
Prepared by Sujeet Lohan
11
Automatic Arithmetic Overflow Checking

Examples:
let y: Int8 = 120
let z = y + 10 // this will give you an error due to over flow because compiler infers the type of z
to be Int8
--------------------------------
Using an overflow operator:
let y: Int8 = 120
let z = y &+ 10
print(“120 &+ 10 is \(z)”)
For other operators: &- for minus, &* for multiplication etc.

Prepared by Sujeet Lohan


12
Converting between Integer Types

Examples:
let a: Int16 = 200
let b: Int8 = 50
let c = a + b // so this is not allowed, compile type error
// There is no automatic conversion in Swift
let c = a + (Int16) b // Explicit type conversion
- -------------------------------

Prepared by Sujeet Lohan


13
Examples of String Interpolation
To perform string interpolation, insert a backslash(\) followed by a set of parenthesis containing the constant,
variable, expression or literal value that you would like to insert at that position in the String literal
//Example #1:
import Cocoa
let name = "Sujeet Lohan"
print("Welcome to Swift Programming, \(name)")
//Example #2:
import Cocoa
var name = "Banyan tree"
var age:Int = 200
let country = "India"
print("Life of \(name) is more than \(age) years in \(country)")
Prepared by Sujeet Lohan
14
Use of keyword let for constants

// Addition program that displays the sum of two integers


import Cocoa
let number1 = 45 // keyword let declares a constant
let number2 = 72
let sum = number1 + number2
print("number1 = \(number1)")
print("number2 = \(number2)")
print("sum = \(sum)")

Prepared by Sujeet Lohan


15
Data Types,
declaration,
Initialization and
Displaying Values

Prepared by Sujeet Lohan


16
Decision Making and if conditional statement

//Compare integers using if statements, relational operators and equality operators


import cocoa
let number1 = 1000; let number2 = 2000
if number1 == number2 { print("\(number1) == \(number2)") }
if number1 != number2 {
print("\(number1) != \(number2)") }
if number1 < number2 {
print("\(number1) < \(number2)") }
if number1 > number2 {
print("\(number1) > \(number2)") }
if number1 <= number2 {
print("\(number1) <= \(number2)") }
if number1 >= number2 {
print("\(number1) >= \(number2)") }
Prepared by Sujeet Lohan
17
Decision Making and if ...else conditional statement

import cocoa
var population: Int = 5500
var message: String
if population < 10000 {
message = “\(population) is a small town” }
else {
message = “\(population) is pretty big” }
print(message)

Prepared by Sujeet Lohan


18
Decision Making and nested if conditional statement

//Use of nested if
import cocoa
var population: Int = 5500
var message: String
if population < 10000 {
message = “\(population) is a small town” }
else {
if population > 10000 && population < 50000 {
message = “\(population) is a medium town” }
else {
message = “\(population) is pretty big” }
}
print(message)
Prepared by Sujeet Lohan
19
Introduction to Swift
Programming – Logical
Operators

Prepared by Sujeet Lohan


20
Introduction to Swift Programming - Switch

u Switch
Basic syntax of a switch statement:

switch aValue {
case someValueToCompare:
// Do something to respond
case anotherValueToCompare:
// Do something to respond
default:
// Do something when there are no matches
}

Prepared by Sujeet Lohan


21
Introduction to Swift Programming - Switch
//Listing 5.1 Your first switch //Create a new Xcode project/playground called Switch and set up a switch
import Cocoa

var statusCode: Int = 404


var errorMessage: String
switch statusCode {

case 400:
errorMessage = "Bad request"

case 401:
errorMessage = "Unauthorized"
case 403:

errorMessage = "Forbidden"
case 404:

errorMessage = "Not found“


default:
errorMessage = "None“ } // end switch
Prepared by Sujeet Lohan
22
Introduction to Swift Programming - Switch
//Listing 5.1 Your first switch //Create a new Xcode project/playground called Switch and set up a switch
u import Cocoa

u let semesterCode: Character = "W"


u switch semesterCode {
u case "S", "s":
u print("Summer Semester")
u case "W", "w":
u print("Winter Semester")
u case "F", "f":
u print("Fall Semester")
u default:
u print("Incorrect Semester Code")
u }
Prepared by Sujeet Lohan
23
Introduction to Swift
Programming – Loops –
for loop

Prepared by Sujeet Lohan


24
Introduction to Swift
Programming – Loops –
for loop

Prepared by Sujeet Lohan


25
Introduction to Swift
Programming – Loops
break and continue

Prepared by Sujeet Lohan


26
Introduction to Swift
Programming – Loops
while var product = 3

while (product <= 100)


{
product *= 3
}

print(product)

Prepared by Sujeet Lohan


27
Introduction to Swift
Programming – Loops
repeat .. while

repeat {

print("\(counter) ")

counter += 1

} while counter <= 10

Prepared by Sujeet Lohan


28
Introduction to Swift Programming - Switch

Ø [Link]
Ø [Link]
Ø Swift for Programming by Deitel and Deitel
Ø Swift Programming 2nd Edition by Matthew Mathias and John Gallagher
Ø IOS Programming 6th Edition by Christian Keur and Aaron Hillegass
Ø [Link]
Ø [Link]
Ø [Link]
Ø Code Repositories on GitHub
Ø Resources on internet

Prepared by Sujeet Lohan

You might also like