Swift Basic Understanding

Hello Everyone
I am new to swift and i am learning from scratch so sorry if I am having hard time to understand, I have this code down here and I don't get why it prints every time i set a value to progress.amount even though I don't call print or even the struct (Note:I have experienced other languages like c# and c):

import Foundation

struct Progress {   var task: String   var amount: Int{     didSet {       print("(task) is now (amount)% Complete")     }   } } var progress = Progress(task: "Loading Data", amount: 0) progress.amount = 50 progress.amount = 99 progress.amount = 100

And as a newbie to swift which projects would you suggest me to make to improve my skills, I would be glad to learn swiftui too if necessary

Replies

Welcome to the forum.

I reformatted the code with code formatter and numbered the lines to make it readable. You should do it in your next posts:

1. import Foundation
2. struct Progress {
3.     var task: String
4.     var amount: Int {
5.         didSet {
6.             print("\(task) is now \(amount)% Complete")
7.         }
8.     }
9. }
10. var progress = Progress(task: "Loading Data", amount: 0)
11. progress.amount = 50
12. progress.amount = 99
13. progress.amount = 100

You had errors line 6. If you want to print the value of a var, you need to use () and not only ()

With this you get:

Loading Data is now 50% Complete
Loading Data is now 99% Complete
Loading Data is now 100% Complete

.

I don't get why it prints every time i set a value to progress.amount even though I don't call print or even the struct 

That's wrong: you do call a print in the struct, in the didSet.

Each time you change (set) amount, the code in the didSet is executed, and it has a print statement.

didSet is called an Observer (it observes changes to the var).

  • Hey

    How do I put my code in code formatter?

    2)To be honest I tried this code from a website while learning so according to the website, My attention to the code was about why it prints every time but I got my answer and by the way could you please explain me when and why do I need a init() function inside struct declaration? (it reminds me python and I do not like it 🤮)

Add a Comment

Hey,

  1. I intended to print it like that however I was just wondering why is it being called every time but I got my answer I was looking for so thank you very much
  2. What project would you suggest me to make in swift/swiftui? (I have some experience in coding language so I am not that newbie)

Thanks for informing me