How to prevent building objects in Swift

What methods do you know to prevent the creation of an object using the Swift programming language?

In C ++, I can just make the constructor the same:

struct A {
 private:
  A() {};
};

int main()
{
  // Doesn't compile because the constructor is private.
  A obj;
  return 0;
}

When I do this in Swift (I tried this on the playground), the code compiles just fine:

class A {
  private init() {}
}

let obj = A()

UPDATE :

Well, this question is marked as a duplicate. But I think this is a misunderstanding. What I'm asking is what you know to prevent objects from being created in Swift. All I want to achieve is to make it clear to the users of my class that it should not be constructive.

UPDATE 2:

Since this question is still here, I think he needs further clarification for those who still cannot understand what I really want.

, , :

class Constants {
 static let someConstant1 = "CONSTANT_VALUE1"
 static let someConstant2 = "CONSTANT_VALUE2"
 //....etc...
}

:

  • ;
  • private init() {}, ;
  • init? nil, , , .

, .

+4
2

Apple Swift:

. , .

- , .

, Dog.swift, :

import Foundation

class Dog {
    private init() {
        print("hello")
    }
}

class Cat {
    var d = Dog()
}

ViewController.swift :

override func viewDidLoad() {

    let c = Cat()  //=>hello

}

:

override func viewDidLoad() {

    let d = Dog() 

}

Xcode , :

"" ,

:

class A {
    init?() {
        return nil
    }

    func greet() {
        print("hello")
    }
}

let x = A()

if let x = x {
    x.greet()
}
else {
    print("nice try")  //=> nice try
}
+2

, , ,

 private class My {
  static var singletonObj = My()
 } 

let obj = My() // error
let obj1 = My.singletonObj
+1

All Articles