簡體   English   中英

在Swift中訪問類中的靜態變量

[英]Access static variables within class in Swift

ClassName.staticVaribale是在類中訪問靜態變量的唯一方法嗎? 我想要像self這樣的東西,但是為了上課。 class.staticVariable

有兩種方法可以從非靜態屬性/方法訪問靜態屬性/方法:

  1. 如您的問題中所述,您可以在屬性/方法名稱前加上類型的前綴:

     class MyClass { static let staticProperty = 0 func method() { print(MyClass.staticProperty) } } 
  2. Swift 2:你可以使用dynamicType

     class MyClass { static let staticProperty = 0 func method() { print(self.dynamicType.staticProperty) } } 

    Swift 3:你可以使用type(of:) (感謝@Sea Coast of Tibet):

     class MyClass { static let staticProperty = 0 func method() { print(type(of: self).staticProperty) } } 

如果你在靜態屬性/方法中,則不需要在靜態屬性/方法前加上任何東西:

class MyClass {
    static let staticProperty = 0

    static func staticMethod() {
        print(staticProperty)
    }
}

斯威夫特有一種方法可以讓馬塞爾的答案滿足最挑剔的風格指導之神

class MyClass {

    private typealias `Self` = MyClass

    static let MyConst = 5

    func printConst() {
        print(Self.MyConst)
    }
}

當你想要訪問相關的類型聲明時,這使得Self在協議中可用。 我不確定Swift 1,因為從未嘗試過,但在Swift 2中它完美無缺

在未來的Swift 3版本(尚未發布)中,您可以使用Self (是的,帶有大寫)來引用包含的類。 已接受提案,但該功能尚未實施。

例如:

struct CustomStruct {          
 static func staticMethod() { ... } 

 func instanceMethod() {          
   Self.staticMethod() // in the body of the type          
 }          
}

資料來源: https//github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md

您可以通過定義自引用類型來解決此問題。

class MyClassWithALongName {
  typealias CLASS = MyClassWithALongName

  static let staticFoo = "foo"

  func someInstanceMethod() -> String {
    return CLASS.staticFoo
  }
}

雖然風格導游的神可能不贊成。

看起來在Swift 4.2中,內部類和實例變量可以直接訪問靜態變量而不需要類名的前綴。 但是,您仍需要函數中的類名。

class MyClass {
    static let staticProperty = 0
    let property = staticProperty //YES

    class Inner {
        func method() {
            print(staticProperty) //YES
        }
    }

    func method() {
        print(staticProperty) //NO
        print(MyClass.staticProperty) //YES
    }
}

我不喜歡這種情況下的typealias方式。 我的解決方法是:

class MyClass {

   static let myStaticConst: Int = 1
   var myStaticConst:Int {
      return type(of: self).myStaticConst
   }

   func method() {
      let i:Int = myStaticConst
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM