在Swift中,“static var”和“var”的主要区别是什么?有人可以用一些小例子来解释一下这个区别吗?
static var
属于类型本身,而var
属于类型的实例(特定类型的特定值)。例如:
struct Car {
static var numberOfWheels = 4
var plateNumber: String
}
Car.numberOfWheels = 3
let myCar = Car(plateNumber: "123456")
所有车辆都有相同数量的轮子。而且你可以在 Car
类型上进行更改。
要更改车牌号码,您需要拥有 Car
实例。例如,myCar
。
我会给你提供一个非常好的Swifty示例,基于这篇文章。虽然这有点复杂。
想象一下,你在项目中有15个collectionView。对于每一个,你都需要设置cellIdentifier和nibName。你真的想要重写所有代码15次吗?
有一个非常POP的解决方案:
让我们通过编写一个协议来帮助自己,该协议返回我们的ClassName的字符串版本。
protocol ReusableView: class {
static var defaultReuseIdentifier: String { get }
}
extension ReusableView where Self: UIView {
static var defaultReuseIdentifier: String {
return String(Self)
}
}
extension BookCell : ReusableView{
}
对于您创建的每个自定义单元格的nibName
也是如此:
protocol NibLoadableView: class {
static var nibName: String { get }
}
extension NibLoadableView where Self: UIView {
static var nibName: String {
return String(Self)
}
}
extension BookCell: NibLoadableView {
}
所以现在无论我在哪里需要nibName
,我只需这样做
BookCell.nibName
无论何时需要cellIdentifier
,我只需这样做:
BookCell.defaultReuseIdentifier
现在具体回答您的问题。您认为我们需要为每个新的BookCell实例更改cellIdentifier吗?不需要!所有的BookCell单元格都将具有相同的标识符。这不是每个实例都会改变的东西。static
因此被制定出来。
虽然我已经回答了您的问题,但是减少15个collectionView的行数的解决方案仍可以得到显着改进,请参见链接的博客文章。
那篇博客文章已经被NatashaTheRobot转化为视频了。
struct MyStruct {
static var foo:Int = 0
var bar:Int
}
println("MyStruct.foo = \(MyStruct.foo)") // Prints out 0
MyStruct.foo = 10
println("MyStruct.foo = \(MyStruct.foo)") // Prints out 10
var myStructInstance = MyStruct(bar:12)
// bar is not
// println("MyStruct.bar = \(MyStruct.bar)")
println("myStructInstance = \(myStructInstance.bar)") // Prints out 12
numberOfWheels
属性。不存在myCar.numberOfWheels
这样的东西。为什么呢?因为它是类的属性,而不是实例的属性。因此,您可以执行Car.numberOfWheels = 7
。 - mfaani