在Swift中声明一个类之外的私有常量

时间:2023-01-15 16:47:15

When creating private constants in Swift it is possible to declare them within a class,

在Swift中创建私有常量时,可以在类中声明它们,

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?

当在类之外时,范围是创建常量的文件。使用一种方法与另一种方法之间是否有任何其他差异,是否有人对最佳实践有意见?

1 个解决方案

#1


1  

They're accessed differently.

他们的访问方式不同。

In the first case, someFloat is in the scope of SomeClass. It's accessed with SomeClass.someFloat.

在第一种情况下,someFloat属于SomeClass的范围。可以使用SomeClass.someFloat访问它。

In the second case, someFloat is in the module scope. It's accessed with just someFloat.

在第二种情况下,someFloat位于模块范围内。它只使用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.

第一种方法是优选的。在模块名称空间中查找标识符通常比较困难,因为它们很容易被标准库或基础/可可框架中的所有标识符淹没。

#1


1  

They're accessed differently.

他们的访问方式不同。

In the first case, someFloat is in the scope of SomeClass. It's accessed with SomeClass.someFloat.

在第一种情况下,someFloat属于SomeClass的范围。可以使用SomeClass.someFloat访问它。

In the second case, someFloat is in the module scope. It's accessed with just someFloat.

在第二种情况下,someFloat位于模块范围内。它只使用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.

第一种方法是优选的。在模块名称空间中查找标识符通常比较困难,因为它们很容易被标准库或基础/可可框架中的所有标识符淹没。