mattchue
mattchue

Reputation: 121

Using class variables within an instance of a class

I'm trying to use Swift to create an instance of a class (the class being the desired type) but it would seem that when I initialize the instance the class var is not applied to the new instance. I'm sure there's an init call or something that I'm missing, so any help would be greatly appriciated.

class Person: NSObject {

    private struct personNameStruct { static var _personName: String = "" }

    class var personName: String
        {
        get { return personNameStruct._personName }
        set { personNameStruct._personName = newValue }
    }

}

var testPerson: Person
testPerson.personName = "Foo"   //"'person' does not have a member named 'personName'"

Upvotes: 0

Views: 61

Answers (2)

Joru
Joru

Reputation: 4436

It works for me in a Playground if you access the personName variable using the class name person, not the instance name: person.personName = "Foo".

This is because a class variable in Swift is similar to a static variable in languages like Java and C#, in that it is shared between all instances of that class. If you just want a property in your class you shouldn't declare it as class var but just var.

Upvotes: 0

matt
matt

Reputation: 535138

An instance member is referred to through a reference to an instance.

A class member is referred to through a reference to the class.

So, for example:

class Dog {
    class var whatDogsSay : String {
        return "Woof"
    }
    func bark() {
        println(Dog.whatDogsSay)
    }
}

To make a dog bark, make a dog instance and tell it to bark:

let d = Dog()
d.bark()

To find out what dogs say, talk to the dog class:

let s = Dog.whatDogsSay

Upvotes: 1

Related Questions