Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring private constants outside of a class in Swift

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?

like image 410
bmjohns Avatar asked Jun 28 '16 13:06

bmjohns


People also ask

How do you declare constants in Swift?

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).

How do you make a variable private in Swift?

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.

What is private variable in Swift?

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.


1 Answers

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.

like image 159
Alexander Avatar answered Sep 26 '22 22:09

Alexander