Swift類中的靜態vs類函數/變量?

本文翻譯自:Static vs class functions/variables in Swift classes?

The following code compiles in Swift 1.2: 以下代碼在Swift 1.2中進行編譯:

class myClass {
    static func myMethod1() {
    }
    class func myMethod2() {
    }
    static var myVar1 = ""
}

func doSomething() {
    myClass.myMethod1()
    myClass.myMethod2()
    myClass.myVar1 = "abc"
}

What is the difference between a static function and a class function? 靜態函數和函數有什麼區別? Which one should I use, and when? 我應該使用哪一個?何時使用?

If I try to define another variable class var myVar2 = "" , it says: 如果我嘗試定義另一個變量class var myVar2 = "" ,它說:

Class stored properties not yet supported in classes; 類中尚不支持的類存儲屬性; did you mean 'static'? 您是說“靜態”嗎?

When this feature is supported, what will the difference be between a static variable and a class variable (ie when both are defined in a class)? 如果支持此功能,則靜態變量和變量之間有什麼區別(即,當兩者都在類中定義時)? Which one should I use, and when? 我應該使用哪一個?何時使用?

(Xcode 6.3) (Xcode 6.3)


#1樓

參考:https://stackoom.com/question/20LqD/Swift類中的靜態vs類函數-變量


#2樓

static and class both associate a method with a class, rather than an instance of a class. staticclass都將方法與類而不是類的實例相關聯。 The difference is that subclasses can override class methods; 不同之處在於子類可以覆蓋class方法。 they cannot override static methods. 他們不能覆蓋static方法。

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet. class理論上講, class屬性將以相同的方式起作用(子類可以覆蓋它們),但是在Swift中尚無法實現。


#3樓

Regarding to OOP , the answer is too simple: 關於OOP ,答案太簡單了:

The subclasses can override class methods, but cannot override static methods. 子類可以覆蓋方法,但不能覆蓋靜態方法。

In addition to your post, if you want to declare a class variable (like you did class var myVar2 = "" ), you should do it as follow: 除了您的文章之外,如果您想聲明一個變量(就像您對class var myVar2 = ""所做的一樣),還應按以下步驟進行操作:

class var myVar2: String {
    return "whatever you want"
}

#4樓

I tried mipadi's answer and comments on playground. 我在操場上嘗試了mipadi的回答和評論。 And thought of sharing it. 並考慮共享它。 Here you go. 幹得好。 I think mipadi's answer should be mark as accepted. 我認爲mipadi的答案應標記爲已接受。

class A{
    class func classFunction(){
    }
    static func staticFunction(){
    }
    class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
}

class B: A {
    override class func classFunction(){

    }

    //Compile Error. Class method overrides a 'final' class method
    override static func staticFunction(){

    }

    //Lets avoid the function called 'classFunctionToBeMakeFinalInImmediateSubclass' being overriden by subclasses

    /* First way of doing it
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
    */

    // Second way of doing the same
    override final class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }

    //To use static or final class is choice of style.
    //As mipadi suggests I would use. static at super class. and final class to cut off further overrides by a subclass
}

class C: B{
    //Compile Error. Class method overrides a 'final' class method
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){

    }
}

#5樓

I got this confusion in one of my project as well and found this post, very helpful. 在我的一個項目中,我也感到困惑,發現這篇文章非常有幫助。 Tried the same in my playground and here is the summary. 在我的操場上也嘗試過,這裏是摘要。 Hope this helps someone with stored properties and functions of type static , final , class , overriding class vars etc. 希望這對具有存儲的屬性和類型爲staticfinalclass ,重寫class vars等功能的人有所幫助。

class Simple {

    init() {print("init method called in base")}

    class func one() {print("class - one()")}

    class func two() {print("class - two()")}

    static func staticOne() {print("staticOne()")}

    static func staticTwo() {print("staticTwo()")}

    final func yesFinal() {print("yesFinal()")}

    static var myStaticVar = "static var in base"

    //Class stored properties not yet supported in classes; did you mean 'static'?
    class var myClassVar1 = "class var1"

    //This works fine
    class var myClassVar: String {
       return "class var in base"
    }
}

class SubSimple: Simple {
    //Successful override
    override class func one() {
        print("subClass - one()")
    }
    //Successful override
    override class func two () {
        print("subClass - two()")
    }

    //Error: Class method overrides a 'final' class method
    override static func staticOne() {

    }

    //error: Instance method overrides a 'final' instance method
    override final func yesFinal() {

    }

    //Works fine
    override class var myClassVar: String {
        return "class var in subclass"
    }
}

And here is the testing samples: 這是測試樣本:

print(Simple.one())
print(Simple.two())
print(Simple.staticOne())
print(Simple.staticTwo())
print(Simple.yesFinal(Simple()))
print(SubSimple.one())
print(Simple.myStaticVar)
print(Simple.myClassVar)
print(SubSimple.myClassVar)

//Output
class - one()
class - two()
staticOne()
staticTwo()
init method called in base
(Function)
subClass - one()
static var in base
class var in base
class var in subclass

#6樓

There's one more difference. 還有另外一個區別。 class can be used to define type properties of computed type only . class只能用於定義計算類型的類型屬性。 If you need a stored type property use static instead. 如果需要存儲的類型屬性,請使用static

"You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass's implementation." “您可以使用static關鍵字定義類型屬性。對於類類型的計算類型屬性,可以使用class關鍵字來允許子類重寫超類的實現。”

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章