1

I noticed that very popular technique for defining constants in Swift looks like this:

struct Constants {
        static let fileDownloadTimeOut: TimeInterval = 45 * 60
        static let timeout: TimeInterval = 60
        static let perPageCount = 10
        static let usersPerPageCount = 15
}

From one point of view - it looks very neat and nice when it comes to syntax. BUT, the problem I'm finding is an overwhelming usage of static variables.

As far as I know, static variables behave the same way in Swift as those do in C++. Those variables are inited during compile time and remain in the memory till the app is dead.

Problems I'm finding with this approach are next:

1) Polluted RAM. I understand that those times when developers save every byte of the memory has passed, but still it doesn't mean that we should not maintain our storage resources properly.

2) I have a big background of C++ and I'm finding such technique as a "bad taste". I was always discouraged to use static variables for "syntax sugar", and that's why I'm used to create a static variable only when I absolutely need it.

The thing is - I searched web for a quite long time to find some other suggestions to define constants nicely in Swift, but I found absolutely nothing except this approach with a struct with a bunch of static variables.

I understand approach with static let constants when it comes to creating Singleton or the object which lives forever till the app dies. But what I noticed that this exact approach is also recommended for usage in view controllers or other temporary objects and logically this is wrong.

Am I overreacting on this trend and that's one of things that changed and accepted by other developers community? I hope to get some opinions on this.

Thanks in advance!

Eugene Alexeev
  • 1,152
  • 12
  • 32
  • Have you looked into this answer : https://stackoverflow.com/questions/37806982/difference-between-static-function-and-singleton-class-in-swift/37812213#37812213 – Razi Tiwana Apr 08 '19 at 18:53
  • Hello @RaziTiwana! Although this is a very valid opinion I'm not sure it fits my question. Are you implying that addressing static constant is a lot faster than addressing a usual variable? – Eugene Alexeev Apr 08 '19 at 18:57

0 Answers0