2017-02-16 37 views
0

我正在嘗試使我可以在我的應用程序中使用的全局變量。我想我可以把東西放在AppDelegate類中,並且隨處可用,如果你知道更好的方法,請告訴我。Swift AppDelegate結構用法

當我嘗試製作一個結構體時,我遇到了問題。我的代碼:

struct category { 
    let one: UInt32 = 0x1 << 1 
    let two: UInt32 = 0x1 << 2 
    let three: UInt32 = 0x1 << 3 
    let four: UInt32 = 0x1 << 4 
} 

,當我嘗試訪問任何類我得到的錯誤

Instance member 'one' cannot be used on type 'category' 

我使用也試過:

struct category { 
    let one: UInt32 { 
     get { 
      return 0x1 << 1 
     } 
    } 
} 

而且也不能工作。

回答

2

首先,應用程序代表沒有什麼特別之處。只要它在自己的範圍內(不包含在任何內容中),你可以在任何地方創建一個全局變量。

其次,你得到的錯誤是因爲你創建的let是實例變量,這意味着你需要一個類的實例。所以你可以說

let myCategory = category() 
let one = myCategory.one 

但是這可能不是你想要的,如果你想要一個全局常量。使let小號static,如果你不希望有創建對象的一個​​實例:

struct category { 
    static let one: UInt32 = 0x1 << 1 
    static let two: UInt32 = 0x1 << 2 
    static let three: UInt32 = 0x1 << 3 
    static let four: UInt32 = 0x1 << 4 
} 

let one = category.one 

第三,你應該利用結構名稱(Category),並在Swift language guide讀了所有的這種解釋。

+0

非常感謝! –