Sean
Sean

Reputation: 3095

Swift Type property for stored property in class

Since Type property is not supported for object stored property, having struct type property seems reasonable workaround to me. Question: should I use inner struct or not?

I like the inner struct syntax because it seems encapsulate the interface better, but I am not sure if it would waste valuable memory space for every instance? will it?

For example

class MyClass { 
  // inside the class
  struct MyStatic {
    static let MyConstant = "abc"
  }
}

or

// in the same file
struct MyStatic {
  static let MyConstant = "abc"
}

class MyClass {

}

Upvotes: 0

Views: 1365

Answers (1)

Mike S
Mike S

Reputation: 42325

If you want the closest approximation to a Type Property, then you'll want to use an inner struct; it won't be stored in every instance of the class. If you define the struct outside your class, then it'll become global, which is not the same thing.

struct defined outside class:

struct MyStatic {
    static let MyConstant = "abc"
}

class MyClass1 {
    func test() { println(MyStatic.MyConstant) } // Works because MyStatic is Global
}

class MyClass2 {
    func test() { println(MyStatic.MyConstant) } // Works because MyStatic is Global
}

struct defined inside class:

class MyClass1 {
    struct MyStatic {
        static let MyConstant = "abc"
    }
    func test() { println(MyStatic.MyConstant) }
}

class MyClass2 {
    func test() { println(MyStatic.MyConstant) } // Compile error: MyStatic is not accessible
}

This also allows you to re-define MyConstant per class (which is what Type Properties are for to being with):

class MyClass1 {
    struct MyStatic {
        static let MyConstant = "abc"
    }
    func test() { println(MyStatic.MyConstant) } // abc
}

class MyClass2 {
    struct MyStatic {
        static let MyConstant = "def"
    }
    func test() { println(MyStatic.MyConstant) } // def
}

You can even add a computed Type Property to simulate a stored one:

class MyClass1 {
    struct MyStatic {
        static let MyConstant = "abc"
    }

    class var MyConstant: String {
        get { return MyStatic.MyConstant }
    }

    func test() { println(MyClass1.MyConstant) }
}

Upvotes: 1

Related Questions