Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I see some variables used with leading dot? [duplicate]

Tags:

swift

Consider the following piece of swift code

view1.autoPinEdge(.top, toEdge: .bottom, ofView: view2)

what is going on with .top, .bottom?

1) Why is this seemingly ambiguous way of specifying a variable allowed?
2) How does swift handle the situation where there are many possible .top and .bottom?

like image 697
AlanSTACK Avatar asked Jan 24 '18 08:01

AlanSTACK


2 Answers

The method is (most likely) declared as

func autoPinEdge(_ from: UIRectEdge, toEdge: UIRectEdge, ofView: UIView)

so the compiler knows that the type of the first two parameters is UIRectEdge.


The full syntax to call the method is

view1.autoPinEdge(UIRectEdge.top, toEdge: UIRectEdge.bottom, ofView: view2)

but as the compiler knows (the documentation says can infer) the type you can pass only the members

view1.autoPinEdge(.top, toEdge: .bottom, ofView: view2)
like image 117
vadian Avatar answered Sep 20 '22 11:09

vadian


This is just a shorthand way of using an enum value.

for example, using the function...

func applyColour(_ colour: UIColor) {
   // apply the colour
}

Could be called using the following syntax

applyColour(UIColor.red)

or

applyColour(.red)

Because the compiler knows that the function is expecting a UIColor parameter. So it can imply the type when you use .red

You can also use type inference with static functions and variables like so:

extension String {
   static var headerText {
        return "This is the header"
   }
}

Usage:

headerLabel.text = .headerText

or:

let heading: String = .headerText
like image 28
Scriptable Avatar answered Sep 23 '22 11:09

Scriptable