Deekor
Deekor

Reputation: 9499

How do you make a static class in swift?

I want to create a static class in swift, is this possible? If so how?

I tried:

static class MyClass

but get the error Declaration cannot be marked 'static'

Upvotes: 2

Views: 1840

Answers (2)

Cœur
Cœur

Reputation: 38667

static means no instance, so I would make it a struct with no initializer:

struct MyStruct {
    @available(*, unavailable) private init() {}

    static var foo = "foo"

    static func doSomething(a: String) -> String {
        return a + foo
    }
}

Upvotes: 1

Antonio
Antonio

Reputation: 72750

There's no static class, but you can make one by just adding static methods only.

The problem is that (as of today) classes cannot have static properties, so you have 2 options:

  • use a struct instead of a class, defining all its methods and properties as static
  • use the singleton pattern

The second option is in my opinion a better solution, unless you have specific reason for not wanting it.

Upvotes: 3

Related Questions