【问题标题】:Differences between "static var" and "var" in SwiftSwift 中“static var”和“var”的区别
【发布时间】:2015-01-29 06:03:23
【问题描述】:

Swift 中“static var”和“var”的主要区别是什么?有人可以用一个小例子向我解释一下这个区别吗?

【问题讨论】:

    标签: swift static var


    【解决方案1】:

    static var 属于类型本身,而var 属于类型的实例(特定类型的特定值)。例如:

    struct Car {
        static var numberOfWheels = 4
        var plateNumber: String
    }
    
    Car.numberOfWheels = 3
    let myCar = Car(plateNumber: "123456")
    

    所有汽车都有相同数量的车轮。您可以在 Car 类型本身上更改它。

    要更改车牌号,您需要有Car 的实例。例如,myCar

    【讨论】:

    • 仅供参考 myCar 没有numberOfWheels 的属性。没有myCar.numberOfWheels 这样的东西。为什么,因为它是 class instance 的属性。结果你可以做Car.numberOfWheels = 7
    【解决方案2】:

    我会给你一个基于this post 的非常好的 Swifty 示例。虽然这有点复杂。

    假设您有一个项目,您的应用中有 15 个 collectionView。对于每个您必须设置 cellIdentifier 和 nibName。你真的想为你的那 15 次重写所有代码吗?

    你的问题有一个非常POP的解决方案:

    让我们通过编写一个返回类名的字符串版本的协议来帮助自己

    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 的所有单元格都将具有 same 标识符。 每个实例都不会改变。结果是static

    虽然我确实回答了您的问题,但减少 15 个 collectionView 的行数的解决方案仍然可以得到显着改进,因此请参阅链接的博客文章。


    那篇博文实际上已经被 NatashaTheRobot 变成了video

    【讨论】:

    • 这是很棒的 POP 答案。
    【解决方案3】:

    静态变量是结构上的属性变量,而不是结构的实例。请注意,枚举也可以存在静态变量。

    例子:

    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
    

    注意到区别了吗? bar 是在结构的一个实例上定义的。而 foo 是在结构本身上定义的。

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 2019-03-20
      • 1970-01-01
      • 2018-08-02
      • 2021-05-07
      • 2011-09-04
      • 2020-11-06
      • 2013-06-28
      • 2013-08-10
      相关资源
      最近更新 更多