skip to content
anntz.com

swift essentials 2

swift core concepts: structs, classes, protocols, enums

Table of Contents

Structs

struct User {
  let userId: Int
  let name: String
  let age: Int
}


// create an instance of user

var userA = User(userId: 1, name: "Ananta", age: 99)

// let's access the struct state
print("Hi User: \(userA.userId)! Your Name: \(userA.name), Your Age: \(userA.age)")


// Output:
// Hi User: 1! Your Name: Ananta, Your Age: 99


// Structs with default value

struct Car {
  var numberPlate: Int = 0
  let make: String
  var model: String
}

var carA = Car(make: "Toyota", model: "Camry")
var carB = Car(numberPlate: 10, make: "Honda", model: "Accord")

print("CarA: \(carA.numberPlate), \(carA.make), \(carA.model)")
print("CarB: \(carB.numberPlate), \(carB.make), \(carB.model)")

// unless it's not a constant, struct members can be mutated:
carA.numberPlate = 1
print("CarA: \(carA.numberPlate), \(carA.make), \(carA.model)")


/* Output:
CarA: 0, Toyota, Camry
CarB: 10, Honda, Accord
CarA: 1, Toyota, Camry
*/


// Structs with functions as members


struct IPod {
  let storage: Int
  func play() {
    print("Playing song....")
  }
}

var ipod = IPod(storage: 128)
ipod.play()
ipod.


/* Output:
Playing song...
*/

Closures