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

When to anticipate brackets() or dot notation. ?

Forums > SwiftUI

Hi Everyone,

This is my first time postig here, so apologies if this is incorrect in someway.

I've decided after a year of studying Swift and UIKit that learning SwiftUI makes the most sense to me at this point.

Howvever, I'm wonderig if there's any rhyme or reason to how the syntax works? Specifically as it relates to things needing either brackets or dot notations.

For example: If I call for 'Text', I can enter two brackets and make adjustments. So something like "Text().font(.headline)", will make that property a headline type of font.

What I'm wondering is whether there is any type of sysytem so that I could have an easier time anticipating whether or not to try dot notation or a bracket.

Is this making sense? How would someone know where to write a period or a bracket after the've called something like a VStack?

Thanks in advance!

2      

Items followed by parentheses () are generally UI elements in SwiftUI, like Text or Picker.

Items followed by curly brackets {} are generally container elements, like VStack or HStack. These usually do not show up on screen but instead encapsulate other elements and group them together.

Items preceded by a period . are generally modifiers that are applied to one of the above and alter or specialize it in some way.

So, in code like this:

VStack {
    Text("Hello world")
        .font(.headline)
}

VStack is a container that has one Text element inside it. That Text element has a font modifier applied to it to give it the headline style.

You can also have parentheses () on containers, in which case they apply some kind of parameters to adjust the characteristics of the container, like so:

VStack(alignment: .top) {
    //...some elements in here
}

And some UI elements can contain other UI elements, in which case they will be followed by curly brackets {}:

Picker("Flavor", selection: $selectedFlavor) {
    Text("Chocolate").tag(Flavor.chocolate)
    Text("Vanilla").tag(Flavor.vanilla)
    Text("Strawberry").tag(Flavor.strawberry)
}

Hope this makes sense.

3      

It does! Thank you very much for helpig me get on a good path here!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.