When creating private constants in Swift it is possible to declare them within a class,
final class SomeClass: NSObject {
private let someFloat:CGFloat = 12
}
as well as outside of a class.
private let someFloat:CGFloat = 12
final class SomeClass: NSObject { }
When outside of the class the scope is the file the constant is created in. Are there any other differences to using one method over the other, and does anyone have opinions on best practices?
In Swift, constants are declared using the let keyword. In a similar fashion to variables, the let keyword is followed by the name of the constant you want to declare and then a type annotation (a colon, a space and then the type of data you want to store in the constant).
You can give a setter a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing fileprivate(set) , private(set) , or internal(set) before the var or subscript introducer.
Fileprivate and private are part of the access control modifiers in Swift. These keywords, together with internal, public, and open, make it possible to restrict access to parts of your code from code in other source files and modules.
They're accessed differently.
In the first case, someFloat
is in the scope of SomeClass
. It's accessed with SomeClass.someFloat
.
In the second case, someFloat
is in the module scope. It's accessed with just someFloat
.
The first method is preferable. It's generally harder to find identifiers in the module name space, because they can be easily drowned out by all the identifiers in the standard library or foundation/cocoa framework.
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