skip to content
anntz.com

swift essentials 1

variables, constants, data types, types conversion, basic operators, if statements, functions, try/catch

Variables & Constants

a. Variables

var name = "Ananta"
name = "Bastola"

print(name)
// Output: Bastola

b. Constants

let name = "Ananta"
name = "Bastola"  // this will throw error

print(name)

Basic Data Types

a. Integers

let score = 20
print(type(of: score))
// Int
// Swift will automatically infer the data type from the initialization variable

let age = 27
print(age.isMultiple(of: 3))
// Output: true

let id = Int.random(in: 1...1000)

b. Decimals

let score = 20.0
print(type(of: score))
// Double
// Swift will automatically infer the data type to Double because we initialized the constant with a decimal value

let age = 27
print(age.isMultiple(of: 3))
// Output: true

let id = Int.random(in: 1...1000)

c. Booleans

let lovesVideoGames = true
lovesVideoGames.toggle() // equivalent to: lovesVideoGames = !lovesVideoGames
print(lovesVideoGames)
// Output: false

d. String

  • Single Line String swift let name = "My name is \"Ananta Bastola \"" print(name) // Output: My name is "Ananta Bastola"

    • Multi Line String

      let movie_script = """
      This constant will store
      multi-line
      string
      """
      print(movie_script)
      // Output:
      // This constant will store
      // multi-line
      // string
    • Basic string operations

      let name = "Hello Ananta"
      
      print(name.count)
      // Output: 12
      
      print(name.hasPrefix("Hello"))
      // Output: true
      
      print(name.hasSuffix("Ananta"))
      // Output: true
      
    • String Interpolation

    let name = "Ananta Bastol"
    let age = 25
    let message = "I'm \(name) and I'm \(age) years old."
    print(message)
    // Output: I'm Ananta and I'm 25 years old.

Arrays

var colors = ["Red", "Blue", "Green"]
var numbers = [1, 2, 3, 4]

print(colors[0]) // Red
print(type(of: colors)) // Array<String>

print(numbers[1]) // Output: 2
print(type(of: numbers)) // Array<Int>


// Append Items in the array
colors.append("Pink")
print(colors) // Output: ["Red", "Blue", "Green", "Pink"]

colors.remove(at: 0)
print(colors.count)// 3
print(colors) // Output: ["Blue", "Green", "Pink"]

Basic Type Annotations

var item: Int = 0
var item_double1: Double = 1
var item_double2: Double = 1.0

let name: String = "Ananta"
var isEnabled: Bool = true


var albums: [String] = ["8Miles", "Revival"]
var user: [String: String] = ["username": "anantab"]
var books: Set<String> = Set(["Atomic habits", "Foundation"])

var teams: [String] = [String]()

Conditions

a. If-else

let age = 16

if age < 12 {
  print("You can't vote.")
} else if age < 18 {
  print("You can vote soon.")
} else{
  print("You can vote now")
}
// Output: You can vote soon.

let temp = 26

if (temp > 20 && temp < 30){
  print("It's a nice day.")
}

if (temp > 20 || temp < 30){
  print("It's a nice day.")
}

b. Switch-case

enum Weather {
  case sun, rain, wind
}

let forecast = Weather.sun

switch forecast {
case .sun:
  print("It's a sunny day")
case .rain:
  print("It's a rainy day")
case .wind:
  print("It's a windy day")
default:
  print("It's hmmmmmm.... day")
}

c. Ternary operator

let age = 18
let voteStatus: String = age >= 18 ? "Yes" : "No"
print(voteStatus) // Yes

Loops

let berries = ["raspberry", "mulberry", "blueberry", "strawberry"]

for berry in berries {
  print("I like \(berry)")
}
// Output:
// I like raspberry
// I like mulberry
// I like blueberry
// I like strawberry


for i in 1...4 {
  print("\(i)")
}
// Output:
// 1
// 2
// 3
// 4


var count = 10

while count > 0 {
  print("\(count)...")
  count--
}
// Output:
// 10...
// 9...
// 8...
// 7...
// 6...
// 5...
// 4...
// 3...
// 2...
// 1...

Functions

func greetUser(username: String){
  print("Hello \(username), hope you have a good day.")
}

greetUser(username: "Ananta")
// Output: Hello Ananta, hope you have a good day.


func rollDice() -> Int{
  Int.random(in: 1...10)
  // if there's a single line, no return keyword required.
}

print(rollDice())
// Output: prints a number within 1 and 10.


// Destructuring in swift
func getUser() -> (firstName: String, lastName: String, email: String) {
  (firstName: "Ananta", lastName: "Bastola", email: "[email protected]")
}

let (firstName, _) = getUser()
print("Name: \(firstName)")
// Output: Name: Ananta

// Default Parameters
func greet(_ name: String  = "Default") {
  print("Welcome, \(name)")
}

greet()
greet("Ananta")
/* Output:
Welcome, Default
Welcome, Ananta
*/

Try/Catch


enum PasswordError: Error {
  case short, obvious
}

func checkPassword(_ password: String) throws -> String {
  if password.count < 5 {
    throw PasswordError.short
  }

  if password == "12345"{
    throw PasswordError.obvious
  }
  if password.count < 10 {
    return "OK"
  }else{
    return "GOOD"
  }
}

do {
  let result = try checkPassword("12345")
  print("Rating: \(result)")
} catch PasswordError.obvious {
  print("I have the same combination on my luggage!")
} catch {
  print("There was an error.")
}

// Output:
// I have the same combination of pw