Swift Basics
Swift is a programming language made by Apple. It’s used for making apps for iPhones, iPads, and Macs. It takes good points from older languages like C and Objective-C but is safer and has new, easy features.
- You can see your code results fast with something called Playground.
- It works with older code from Objective-C and can use big libraries like Cocoa.
- You can mix styles like making lists of steps and working with objects.
- You don’t always need to end lines with a semicolon, only if you write more than one instruction on the same line.
- Use ‘var’ for things that can change, and ‘let’ for things that don’t change.
- Swift is smart and can guess what type your data is, like numbers or text.
- You can use any language’s letters for names in your code.
- It’s better to use ‘let’ when you know your data won’t change.
- Sometimes data can be nothing (nil), and Swift handles that safely.
- The ‘switch’ statement in Swift can work with different types and doesn’t need ‘break’ like other languages.
- You don’t need brackets for ‘if’ statements.
- Functions can have default values and can change the number of inputs.
- Blocks of code, called closures, are simpler than in Objective-C.
- You don’t have to use header files in Swift.
- You can skip mentioning a base class; it doesn’t have a single one for everything.
- Swift doesn’t separate the idea of properties and instance variables.
- You can group values together with something called tuples.
- Comments can be nested inside each other.
- ‘typealias’ lets you give a new name to a type.
- ‘nil’ in Swift is the absence of a value, different from Objective-C.
- You can use ‘!’ to say that a variable will have a value for sure.
- Assertions can stop the code if something is really wrong.
- Swift’s strings are copied when you pass them around, so they’re safer.
- You can use optional binding and chaining for safer code.
Variables and Constants
- ‘var’ is for things that change. ‘let’ is for things that stay the same.
- Swift uses type inference, so it figures out what type of data your variable is.
- You can use different types of data like text (String), whole numbers (Int), big numbers with decimal points (Double), small numbers with decimal points (Float), and true/false values (Bool).
- Combining text with variables is easy in Swift. You can add strings together or put variables directly into strings with (variable).
var myName = "Ravi" // 'var' for a value that can change let pi = 3.14 // 'let' for a constant value that won't change
// Variables and Constants var myStr = "Swift" // Implicit variable declaration or type inference var myValue = 23.1 // Implicit type inference to Double var myDoubleValue: Double = 23 // Explicit variable declaration // Constants let myAge = 38 // Converting value to a String by concatenation let message = "My age is " + String(myAge) // Converting value to a String using string interpolation let newMessage = "My age is \(myAge)"
Data Types
let cityName: String = "Mumbai" let population: Int = 20_000_000 let temperature: Double = 26.7 let hasMonsoon: Bool = true
Collection Types
- Arrays are lists of items. You can add, remove, and sort these items easily.
- Dictionaries are collections of items you can find with a key.
Arrays
// Array Declarations var fruits: [String] = ["Orange", "Apple", "Grapes"] // Short declaration with type // Insert item at index fruits.insert("Mangoes", at: 2) // Append item to the last fruits.append("Pineapple") // Count of array let count = fruits.count // Remove item at index fruits.remove(at: 1) // Sort array elements fruits.sort { (a, b) -> Bool in return a < b } // Retrieve index of an item if let mangoIndex = fruits.firstIndex(of: "Mangoes") { print("Mangoes found at index: \(mangoIndex)") } else { print("Mangoes not found") }
Dictionaries
// Dictionary Declaration var employees: [Int: String] = [1: "John", 2: "Peter", 3: "David"] // Short form with type // Add new item to dictionary employees[4] = "Bob" // Remove an item using key employees.removeValue(forKey: 3)
Operators
- Swift has operators for adding, subtracting, multiplying, and dividing.
- You can also compare things with ==, !=, >, <, >=, and <=.
- The ‘!’ operator can flip a true/false value.
- ‘&&’ means ‘and’, ‘||’ means ‘or’.
Let’s break down these concepts into simpler terms:
Assignment Operator
a = b
: This means you’re makinga
the same asb
. Whatever valueb
has,a
will have it too.let (a, b) = (2, 3)
: This lets you seta
to 2 andb
to 3 at the same time. It’s a quick way to give values to multiple things.
Arithmetic Operators
- Addition (
+
): Adds two numbers together or joins two pieces of text. - Subtraction (
-
): Takes one number away from another. - Multiplication (
*
): Multiplies two numbers. - Division (
/
): Divides one number by another. - Remainder (
%
): Tells you what’s left over after dividing two numbers. - Increment (
++i
ori++
): Adds 1 to a number.++i
adds before using the number,i++
adds after. - Decrement (
--i
ori--
): Subtracts 1 from a number.--i
subtracts before using the number,i--
subtracts after. - Unary Minus (
-x
): Makes a number negative. - Unary Plus (
+x
): Keeps a number positive (usually not needed).
Compound Assignment Operator
x += 2
: Adds 2 tox
. It’s a shortcut forx = x + 2
.
Comparison Operators
x == y
: Checks ifx
is equal toy
.x != y
: Checks ifx
is not equal toy
.x > y
: Checks ifx
is greater thany
.x < y
: Checks ifx
is less thany
.x >= y
: Checks ifx
is greater than or equal toy
.x <= y
: Checks ifx
is less than or equal toy
.===
and!==
: Used to check if two object references point to the same object.
Ternary Conditional Operator
a = flag ? 10 : 20
: Setsa
to 10 ifflag
is true, otherwise sets it to 20. It’s a short way of saying “if-else.”
Range Operators
- Closed Range (
1...10
): Includes the numbers 1 through 10. - Half-Closed Range (
1..<10
): Includes 1 through 9, stopping before 10.
Logical Operators
- NOT (
!x
): Changes true to false, and false to true. - AND (
x && y
): True if bothx
andy
are true. - OR (
x || y
): True if eitherx
ory
(or both) are true.
These explanations aim to make the concepts easier to understand without using complex language.
Control Flow
- ‘if’ statements let you do different things depending on what’s true.
- ‘for’ statements let you go through items in a list one by one.
// Control Flow // If-else statements if fruits[0] == "Grapes" { print("for breakfast") } else if fruits[0] == "Apple" { print("for lunch") } else { print("Nothing") } // For loop with an exclusive range for index in 0..<fruits.count { print("\(fruits[index])") }
Functions
- Functions let you group code to do a specific task.
- You can pass information to functions and get results back.
- Swift lets functions have default values for parameters.
- Functions can take a bunch of values with variadic parameters.
- If you want a function to change a value directly, use ‘inout’ parameters.
Let’s reformat your Swift code samples and simplify the explanations:
Basic Function
func sum(number1: Int, number2: Int) -> Int { return number1 + number2 }
This function, sum
, takes two numbers (number1
and number2
) and adds them together. The result is given back as an Int
.
Function Without Parameters
func sum() -> Int { return 10 + 5 }
Here’s a simple function that doesn’t need any inputs. It just adds 10 and 5 together and gives back the result, which is 15.
Function with External Parameter Names
func sum(addNumber1 number1: Int, withNumber2 number2: Int) -> Int { return number1 + number2 } print(sum(addNumber1: 10, withNumber2: 20))
This version of the sum
function uses named parameters to make it clearer what each input represents when the function is called. addNumber1
and withNumber2
are what you see outside, but inside the function, you just refer to number1
and number2
.
(Note: The use of #
before parameter names to denote both local and external names is outdated and not used in current Swift syntax.)
Function with Default Parameter Value
func sum(number1: Int, withNumber2: Int = 20) -> Int { return number1 + withNumber2 } print(sum(10))
This function lets you add two numbers, but if you don’t provide the second number, it will use 20 by default. So, if you just give it 10, it adds 10 and 20 together and returns 30.
Variadic Parameters
func totalSum(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } totalSum(1, 2, 3, 4, 5)
The totalSum
function can take any number of integer inputs and adds them all together. The ...
after Int
in the parameters means you can input as many Int
values as you want.
Inout Parameters
var employee = "Ravi" func greetings(employee: inout String) { employee += "!" } greetings(employee: &employee) print(employee)
An inout
parameter allows a function to modify a variable outside the function. In this example, the greetings
function adds an exclamation mark to the employee
variable’s value. The &
before employee
when calling the function indicates that it can be modified by the function.
Remember, Swift is friendly for new programmers and powerful for the pros. It’s meant to be easy to read and write, making app creation fun and accessible. Happy coding!
Leave a Reply