0

I have a class that looks like this:

class A {
    var aString = ""
    static var staticString = ""
}

If I create an instance of A I can't access the static property:

var a = A()
a.staticString = "THIS GIVES AN ERROR"

However, if I create a direct instance to the static variable it works:

var a = A.staticString
a = "THIS WORKS"

The way I understand static variables is that you should only be able to access them directly like this: A.staticString = "hello". But this doesn't seem to be the case.

What's more confusing (to me) is that I can create multiple instances with their own seperate values; that is the value doesn't remain static:

var a = A.staticString
a = "AAA"

var b = A.staticString
b = "BBB"
print(a) //prints AAA
print(b) //prints BBB

Isn't the whole point that a static variable should... remain static? In my head, both a and b should print BBB since b = "BBB" should have overwritten the first value assigned to it.

To make it even more confusing (to me), using a singleton does give me the result I expect:

class A {
    static let shared = A()
    var aString = ""
    static var staticString = ""
}
let instance1 = A.shared
instance1.aString = "A String"
        
let instance2 = A.shared
instance2.aString = "Another String"
        
print(instance1.aString, instance2.aString) //Both print "Another String"

Could some kind soul try to clear things up for me?

2
  • 1
    The variable remains static, you just copy it to a and b, they have nothing to do with the static variable, just two string varaibles. Commented Jul 23, 2020 at 10:51
  • static is not the same as constant (let). Commented Jul 23, 2020 at 10:51

1 Answer 1

1

The static keyword in Swift does not mean the property is immutable/constant (unlike in C-based languages). static means the property is a type property, not an instance property, meaning that it is a property of the type itself, shared between all instances and not a property of each instance. For more information, read the Type Properties section of the Swift language guide.

Constants/immutable properties are declared by let, while mutable ones by var.

You can set and get static vars by using the type name (A in your case).

A.staticString = "new"
A.staticString // "new"

If you create instances of the type, you can use type(of:) to get the meta-type (A), which you can use to access static properties

let a = A()
type(of: a).staticString // "new"
let anotherA = A()
type(of: anotherA).staticString  // "new"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.