TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.