DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on

Day 8 of 100 days of SwiftUI

Day 8 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about Structs.

Structs in Swift are used to define your own custom data types. Structs can have variables, constants, and functions. Variables and constants in Structs are known as properties while functions are known as Methods. Structs in Swift can be written like so.

 struct Person {
   var name: String
   var nationality : String
   var level: Int

   func checkLevel() -> Bool {
       if level > 9000 {
         print("It's over 9000!")
       } else {
         print("hmmmmm.... not bad.")
       }
   }
}

let sanmi = Person(name: "sanmi", nationality: "Nigerian", level: 9001)
sanmi.checkLevel()
Enter fullscreen mode Exit fullscreen mode

The code above defines a structure(struct) with three variables and one method. Methods are pretty much functions inside a struct. There are two noticeable differences between methods and functions.

  • Methods have access to properties defined in a struct. You can see in the checkLevel method, we are checking to see if the level property is above 9000.
  • There are two kinds of methods in Swift. Mutating methods and non-mutating methods. Mutating methods are used when you want to change a properties value. Mutating method are simply marked as mutating.
 struct Engine {
   var name: String
   var speed : Int = 150

   mutating func upgrade() {
     speed += 50
   }
}

let engine = Engine(name: "Tron")
engine.upgrade()
Enter fullscreen mode Exit fullscreen mode

Properties in Swift have this really cool feature called property observers. Properties observers let you run a piece of code before and after the property changes. Property observers are very simple to use in swift.

 struct Engine {
   var name: String
   var speed : Int = 150
        didSet {
            print("Engine speed was changed to \(speed)")
        }
        willSet {
            print("Engine speed is about to be  changed")
        }

   mutating func upgrade() {
     speed += 50
   }
}

let engine = Engine(name: "Tron")
engine.upgrade()
Enter fullscreen mode Exit fullscreen mode

If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)

Top comments (0)