2

I am new to Swift and stuck in a problem.

When I use optional let inside a class it is giving the error "Class className has no initializers".

But when I write the same code using optional var, it shows no error.

For example:

The following code give me error:Class className has no initializers

class className: UIViewController
{
    let nearbyPlaceRadius : Int?    

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
}

The following code gives me no error.

class className: UIViewController
{
    var nearbyPlaceRadius : Int?    

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
PGDev
  • 23,751
  • 6
  • 34
  • 88

2 Answers2

5
    let nearbyPlaceRadius : Int?   

Actually you can have above line in your code and its not wrong. But if you do so, you have to write an init method and set it's value inside that method.

Rukshan
  • 7,902
  • 6
  • 43
  • 61
2

The problem is that let is immutable. Once you have defined a variable or object using let keyword you can't change it, while using var you can mutate it any time.

That's the reason, it say class has no initializers

let someThing: Int? //Wrong
let someThing: Int = 100 //Correct 

For reference: What is the difference between `let` and `var` in swift?

Update:

You can use let keyword with initializer.

let name: String?

init (name: String) {
    println("Initializing: \(name)")
    self.name = name
}
Community
  • 1
  • 1
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • But even if I don't initialize a value to it, it must take it as nil since it is an optional constant. – PGDev Mar 21 '16 at 05:52
  • Nope, for `let` keyword it will not work! But if you will declare `let` with `nil` what will be the purpose of it ? Bcaz you can assign any value to it later? @PGDev – Sohil R. Memon Mar 21 '16 at 05:54
  • @SohilR.Memon the question was about optional let. – Darko Mar 21 '16 at 11:50