Swift-Basics
Tags: swift
Published: 2021-12-20 06:08:42

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

## Constants and variables

These constants and variables associates a name with value of particular type.

**Declaring constants and variables:**

- They should be declared before we use them.
- To declare constant use **"let"** keyword.
- To declare variable use **"var"** keyword.

```swift
let maximumNumberOfLoginAttempts = 10 
var currentLoginAttempt = 0 
```
- We can declare multiple constants or variable on a single line separated by commas

```swift
var x = 1,y = 2,z = 3
```
## Type Annotations 
We can provide a type annotation when we declare a constant or variable to be clear about the type of variable the constant or variable can store.

```swift
var welcomeMessage:String = "Hello" 
//this can be read as welcomeMessage is ...of...type...String
```
This means it can store any string values.

- We can define multiple related variables of the same type on a single line separated by commas ,with a single type annotation after the final variable name.

```swift
var red,blue,green:Double
```
**Note:** It is rare that we write type annotations in practice.

## Naming constants and variables
- Can contain any characters including unicode.
**Constants and variables cannot contain,**
- whitespace character
- mathematical symbol (<,>,=...>)
- arrows
- private use unicode private values
- lines and box-drawing characters
- and cannot start with numbers

we can use reserved swift keywords as names using backticks


## Printing constants and variables
```swift
print(_:seperator:terminator:)
```
this **print** is an global function that prints one or more values to an appropriate output.

both **separator** and **terminator** has default value so they can omitted 

- seperator default value -> (" ")
- terminator default value -> ("\n")
 
## String interpolation
```swift
var name = "Ajith"
print("my name is \(name)")
```
- This is a way to construct a new string values from a mix of constants,variables,literals and expression.
Each item that we insert into the string literals are wrapped in a pair of paranthesis , prefixed by backslash (\)
- we can use extended string delimiters to create  string containing characters that would otherwise be treated as a string interpolation.

```swift
print(#"my name is \(name)"#)
```
## Comments
non-executable text in your code

```swift
//single line comment

/*multiple line
comment*/
```
## semicolon
swift doesn't require to write semicolon (;)
semicolons are required if we write multiple statements in single line

## Integers 
Integers are whole numbers with no fractional values such as 42,-23 they are either signed or un signed

swift provides signed or un signed integers in 8,16,32 and 64bit forms

## floating point:
- Double (64-bit fp) 15 decimals
- float (32-bit fp) 6 decimals

## Type safty and type inference
- If part of your code requires a string,You cannot pass it an Int by mistake
- If we did't mention the type the swift automatically takes the type as from the initial value.

```swift
let pi = 3.14 //double
let x = 4 // Int
```
## Type alias
Type alias defines a alternate name for an existing type.we define the type alias with the typealias keyword.

```swift
typealias audioSample = UInt16

var maxAudioSample = audioSample.max
```
## Tuples
Tuples group multiple values into single compound value.The value within a tuple can be any type and don't have to be same as each other.

```swift
let person = ("Ajith","madhan")
print(person.0 , person.1) //Ajith madhan

//named tuples

let p =(firstname:"Ajith" , lastname:"madhan")
print(p.firstname , p.lastname) //Ajith madhan

let (firstname,lastname) = person
print(firstname) // Ajith
```

## Optionals
We use optionals in place where a value may be absent.An optional represents two possibilities, either there is a value and you can unwrap the optional to access the value or there isn't any value at all.

```swift
let x = "123z"
let y:Int? = Int(x)
print(y) //nil
```
We can set a optional to a variable to a valueless state by assigning it a special value nil.

```swift
var sourceCode:Int? = 404
sourceCode = nil
```
**note:** we can't use nil with non-optional constant or variables

If we provide a constant value without providing a default value,the variable automatically sets to nil.

**Forced unwrapping**
Once we know that optionals does contain a value, we can access the underlying value by adding a exclamatory mark(!) to the end of the optional name.This "!" says that "I know that the value optional definitely has a value" 
This is also known as forced unwrapping of the optional value.

```swift 
If converteredNumber != nil {
   print("converter number is \(convertedNumber!)")
}
```
```swift
class Xmas {
      func suprise() -> Int {
return Int.random(in:1...10)
   }
}
let present:Xmas? = Xmas()
if present != nil {
    print(present!.suprise())
}
```