Pol*_*les 53 static constants swift
我对在swift中使用static关键字感到有些困惑.正如我们所知,swift引入了let关键字来声明不可变对象.就像声明一个表视图单元的id一样,它最有可能在其生命周期内不会改变.现在什么是在一些struct的声明中使用static关键字:
struct classConstants
{
static let test = "test"
static var totalCount = 0
}
Run Code Online (Sandbox Code Playgroud)
而let关键字也是这样.在Objective C中,我们使用static来声明一些常量
static NSString *cellIdentifier=@"cellId";
Run Code Online (Sandbox Code Playgroud)
除此之外让我更好奇的是使用static关键字以及let和var关键字.谁能解释一下我在哪里使用这个静态关键字?更重要的是我们真的需要swift的静态吗?
Ale*_*ier 111
我会为你打破它们:
var :用于创建变量let :用于创建常量 static:用于创建类型属性与任一let或var.这些在类的所有对象之间共享.现在你可以结合起来,得到所需的结果:
static let key = "API_KEY" :type属性是常量static var cnt = 0 :type属性是一个变量let id = 0 :constant(只能分配一次,但可以在运行时分配)var price = 0 :变量所以总结一下var并让我们在静态和缺乏定义范围时定义可变性.您可能static var用来跟踪已创建的实例数,而您可能只想使用var不同于对象的价格.希望这可以解决一些问题.
示例代码:
class MyClass{
static let typeProperty = "API_KEY"
static var instancesOfMyClass = 0
var price = 9.99
let id = 5
}
let obj = MyClass()
obj.price // 9.99
obj.id // 5
MyClass.typeProperty // "API_KEY"
MyClass.instancesOfMyClass // 0
Run Code Online (Sandbox Code Playgroud)
Bob*_*bby 93
静态变量通过类的所有实例共享.在操场上抛出这个例子:
class Vehicle {
var car = "Lexus"
static var suv = "Jeep"
}
// changing nonstatic variable
Vehicle().car // Lexus
Vehicle().car = "Mercedes"
Vehicle().car // Lexus
// changing static variable
Vehicle.suv // Jeep
Vehicle.suv = "Hummer"
Vehicle.suv // Hummer
Run Code Online (Sandbox Code Playgroud)
更改静态属性的变量时,该属性现在将在以后的所有实例中更改.
Vin*_*ino 10
静态变量属于类型而不是类的实例.您可以使用类型的全名访问静态变量.
码:
class IOS {
var iosStoredTypeProperty = "iOS Developer"
static var swiftStoredTypeProperty = "Swift Developer"
}
//Access the iosStoredTypeProperty by way of creating instance of IOS Class
let iOSObj = IOS()
print(iOSObj.iosStoredTypeProperty) // iOS Developer
//print(iOSObj.swiftStoredTypeProperty)
//Xcode shows the error
//"static member 'swiftStoredTypeProperty' cannot be used on instance of type IOS”
//You can access the static property by using full name of the type
print(IOS.swiftStoredTypeProperty) // Swift Developer
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你..
| 归档时间: |
|
| 查看次数: |
40623 次 |
| 最近记录: |