DEV Community

Ajithmadhan
Ajithmadhan

Posted on • Updated on

Swift-Basics

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.
let maximumNumberOfLoginAttempts = 10 
var currentLoginAttempt = 0 
Enter fullscreen mode Exit fullscreen mode
  • We can declare multiple constants or variable on a single line separated by commas
var x = 1,y = 2,z = 3
Enter fullscreen mode Exit fullscreen mode

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.

var welcomeMessage:String = "Hello" 
//this can be read as welcomeMessage is ...of...type...String
Enter fullscreen mode Exit fullscreen mode

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.
var red,blue,green:Double
Enter fullscreen mode Exit fullscreen mode

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

print(_:seperator:terminator:)
Enter fullscreen mode Exit fullscreen mode

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

var name = "Ajith"
print("my name is \(name)")
Enter fullscreen mode Exit fullscreen mode
  • 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.
print(#"my name is \(name)"#)
Enter fullscreen mode Exit fullscreen mode

Comments

non-executable text in your code

//single line comment

/*multiple line
comment*/
Enter fullscreen mode Exit fullscreen mode

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.
let pi = 3.14 //double
let x = 4 // Int
Enter fullscreen mode Exit fullscreen mode

Type alias

Type alias defines a alternate name for an existing type.we define the type alias with the typealias keyword.

typealias audioSample = UInt16

var maxAudioSample = audioSample.max
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

let x = "123z"
let y:Int? = Int(x)
print(y) //nil
Enter fullscreen mode Exit fullscreen mode

We can set a optional to a variable to a valueless state by assigning it a special value nil.

var sourceCode:Int? = 404
sourceCode = nil
Enter fullscreen mode Exit fullscreen mode

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.

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

Top comments (0)