Swift Basics
Published: 2022-04-01 10:57:11

- Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development.

DataTypes 
- Swift provides **datatype** such as 

1. Int
2. Double
3. Float
4. Bool
5. String 

- 3 primary **collection** types - 

1. Array
2. Set
3. Dictionary



 

**Variables** - to store and refer to these values.
example : 
``` swift
var currentLoginAttempt : Int = 0
```

**Constant** - For variable whose value doesn't change.
example : 

``` swift
let maximumNumberOfLoginAttempts : Int = 10
```

- **tuples** - store group of values
- **optional types** - handles the absence of a value

---

# Type Annotations
provide a type annotation when you declare a constant or variable
example :

``` swift
var welcomeMessage: String
```

---

# DataTypes

###Int
Integers - whole numbers with no fractional component.
Swift provides - signed and unsigned integers in 8, 16, 32, and 64 bit forms

> Range for signed int : -2^(n-1) to (2^(n-1))-1
> Range for unsigned int : 0 to (2^n )- 1

###Floating-Point Numbers
Numbers with a fractional component.

Swift provides two signed floating-point number types:

1. Double represents a 64-bit floating-point number.
2. Float represents a 32-bit floating-point number.

Double - precision of at least 15 decimal digits
Float - 6 decimal digits.

---

###Type Inference
Type inference enables a compiler to deduce the type of a particular expression automatically by examining the values you provide.

example : 

``` swift
let pi = 3.14159  // pi is inferred to be of type Double
```

If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context:

example :

``` swift
let anotherPi = 3 + 0.14159  // inferred as type Double
```

---

###Numeric Literals
Integer literals can be written as:

- A decimal number, with no prefix
- A binary number, with a 0b prefix
- An octal number, with a 0o prefix
- A hexadecimal number, with a 0x prefix

example : 

``` swift
let decimalInteger = 17           // 17 in decimal
let binaryInteger = 0b10001       // 17 in binary
let octalInteger = 0o21           // 17 in octal
let hexadecimalInteger = 0x11     // 17 in hexadecimal
```

###Floating-point literals
Floating-point literals can be decimal (with no prefix), or hexadecimal (with a **0x** prefix). 
Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase **e** and for hexadecimal floats indicated by an uppercase or lowercase **p**

example :

> 1.25e2 means 1.25 x 102, or 125.0.
> 1.25e-2 means 1.25 x 10-2, or 0.0125.

> 0xFp2 means 15 x 22, or 60.0.
> 0xFp-2 means 15 x 2-2, or 3.75.

**_The rules for combining numeric constants and variables are different from the rules for numeric literals_.** 
i.e.

``` swift
let pi = 3 + 0.14159. //Correct

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = three + pointOneFourOneFiveNine  //Compilation Error
let pi = Double(three) + pointOneFourOneFiveNine  //Correct
```

--

###Type Aliases

Type aliases define an alternative name for an existing type. It is useful when you want to refer to an existing type by a name thats contextually more appropriate

example : 

``` swift
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min // it is 0 now
```

---

###Tuples
Tuples group multiple values into a single compound value. The values within a tuple can be of any type.

example : 

``` swift
let http404Error = (404, "Not Found") //type (Int, String)
```

You can name the individual elements in a tuple, when defined

example :

``` swift
let http200Status = (statusCode: 200, description: "OK")
```

use the element names to access the values of those elements:
example : 

``` swift
print("The status code is \(http200Status.statusCode)")
```

---

###Optionals
use optionals in situations where a value may be absent.
optional **variable** without a default value is automatically set to nil, but not constant

forced unwrap an optional value using **!**

example :
``` swift
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
if convertedNumber != nil {
    print("convertedNumber : \(convertedNumber!).")
}

```

**_Trying to use ! to access a nonexistent optional value triggers a runtime error_**

**Optional Binding**
use optional binding to find out whether an optional contains a value, and if so store it in a variable or constant

example : 

``` swift
if let actualNumber = Int(possibleNumber) {
    print("The string has an integer value of \(actualNumber)")
} else {
    print("The string couldn't be converted to an integer")
}
// "The string has an integer value of 123"
```

**_Constants and variables created with optional binding in an if statement are available only within the body. In contrast, in guard statement, it is  available in the lines of code that follows that_**

**Implicitly Unwrapped Optionals**
an optional will always have a value, after that value is first set.

``` swift
let possibleNumber = "123"
let convertedNumber : Int! = Int(possibleNumber)
let number : Int = convertedNumber // ! - not needed
```

**_Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point._**

---

### Basic Operators

- Assignment Operator ( = )
- Compound Assignment Operators ( += , -= etc )
- Arithmetic Operators(+, -, *, /)
- Remainder Operator ( % )
- Unary Minus Operator ( + )
- Unary Plus Operator( - )
- Comparison Operators ( <, >, <=, >= , == , !=)
- Identity operators (=== and !==)
- Ternary Conditional Operator ( ?: )
- Nil-Coalescing Operator
 ( ?? ) - unwraps optional value if it contains else return default value
example :

``` swift
let defaultColorName = "red"
var userDefinedColorName: String?
var colorNameToUse = userDefinedColorName ?? defaultColorName  // "red"
```
- Range Operators 
- Closed Range( a...b )
- Half Open Range( a..<b )
- One-Sided Ranges (...a , a...)
- Logical Operators (!, &&, ||)

**_??, &&, || - uses short-circuit evaluation_**