Jack
Jack

Reputation: 569

Swift AppDelegate Struct usage

I'm trying to make a global variable I can use across my app. I figured out I can put stuff in the AppDelegate class and it will be accessible everywhere, if you know a better way please let me know.

When I try to make a struct I am running in to problems. My Code:

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

and when I try to access that in any class I get the error

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

I also tried using:

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

and That didn't work either.

Upvotes: 0

Views: 272

Answers (1)

Connor Neville
Connor Neville

Reputation: 7361

First, there's nothing special about the App Delegate. You can make a global variable anywhere as long as it's in its own scope (not contained inside anything).

Second, the error you're getting is because the lets you create are instance variables, meaning you need an instance of category. So you could say

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

But this probably isn't what you want if you want a global constant. Make the lets static if you don't want to have to create an instance of the object:

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

Third, you should capitalize struct names (Category) and read up on the Swift language guide where all of this is explained.

Upvotes: 2

Related Questions