UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Question: when to use (), and when to use . dot ?

Forums > 100 Days of SwiftUI

@boat  

Hi, I'am learning how to compue property values dynamically on Day 10 's Struct -themed tutorials.

"https://www.hackingwithswift.com/quick-start/beginners/how-to-compute-property-values-dynamically"

I found it was confusing to decide when to use () and when to use "." , if I want to pass in a value to an instance or to a method.

Here is what Paul wrote :

struct Employee {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0

    var vacationRemaining: Int {
        vacationAllocated - vacationTaken
    }
}
var archer = Employee(name: "Sterling Archer", vacationAllocated: 14)
archer.vacationTaken += 4
print(archer.vacationRemaining)
archer.vacationTaken += 4
print(archer.vacationRemaining)

when I tried to write it in my Playground, I mistakenly wrote

var archer = Employee(name: "Sterling Archer", vacationAllocated: 14)
archer (vacationTaken: 4)
print(archer.vacationRemaining)

Then I reliazed Paul used "." when calling out archer's vacationTaken property.

My question is: Is there a general rule about "When to use . and when to use ()" ?

Or we just need to remember where to use what ?

Thank you in advance

Boat

3      

The . is used to access a property, in this case of the struct Employee. When Paul writes archer.vacationTaken += 4, he's accessing the vacationTaken property and increasing it in 4 units.

The () is generally used to call a function. Print() is a function, so it will print whatever you pass as a parameter (that is, inside the parenthesis).

print(archer.vacationRemaining) -> here you pass in the vacationRemaining property of the employee archer to the function print. Then, the print function will show the value of that property.

Hope it helped.

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.