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
?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With