2

I wanted to create a Swift class to store some data so I wanted to use class variables 'cause I know static variables from Java. So I wrote this code:

class myClass {
    class var myVar:Int = 0
}

But this feature isn't yet supported as the warning said then. So I wanted to ask if there's a way to do that in a nice way. I know this is kinda workin' using computed properties but actually that's not what I really want. I would really love when someone helped me :]

borchero
  • 5,562
  • 8
  • 46
  • 72
  • 1
    use `struct` instead. Structs support static vaiables – Maxim Shoustin Nov 18 '14 at 20:02
  • 1
    Read [this answer](http://stackoverflow.com/a/26567571/148357) - slightly different question but pertinent answer – Antonio Nov 18 '14 at 20:10
  • @Antonio thanks for the link I didn't see that earlier - but when the class variables are supported am I allowed to use them or should I rather use structures instead? – borchero Nov 18 '14 at 20:21
  • 1
    Usage of structs is just a workaround for that limitation - as soon as class (static) properties will be available, it's better to use them. But who know when that's gonna happen... – Antonio Nov 18 '14 at 20:24

1 Answers1

3

Your two options are to use truly global variables:

var myVar: Int = 0

or to use static variables in a struct:

struct MyStruct {
    static var myVar:Int = 0
}

Either of these will have scope that is global to your project/module.

(Note that type names should be capitalized: MyType, not myType.)

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • Thanks for your answer - but can I use class variables when they're supported or should I better use structures instead? P.S. I actually know about class names but I just wrote it down here and didn't think that much about the names LOL – borchero Nov 18 '14 at 20:22
  • 1
    No worries! To be honest there shouldn't be a difference - *instances* of `class` and `struct` are different in that class instances are reference types and struct instances are value types, but if you're just using the type as a repository for static vars it wouldn't matter one way or the other. – Nate Cook Nov 18 '14 at 20:36