When creating an object gives an error

Tell the new, I created the class, at the same time I want to do without the initializer. So I just set the start values and, according to Swift, it should type the type himself, it do not show errors. Then I create an instance of the class, assign values to variables, and get an error. I can not understand why



class Account {
    var capital = 0.0
    var rate = 0.0
  
    var profit: Double {
      
        get {
            return capital + capital * rate
        }
        set(newProfit) {
            self.capital = newProfit / (1 + rate)
        }
    }  
}


var myAcc = Account (capital: 1000.0, rate: 0.1)


Last line gives an error that - argument passed to call that takes no arguments var myAcc = Account (capital: 1000.0, rate: 0.1)

Replies

If you don't want to create a custom initializer, then you shouldn't call a custom initializer.


Given your class definition, you need:


var myAcc = Account()
myAcc.capital = 1000.0
myAcc.rate = 0.1

Just need to create a convenience initializer.


class Account {
    var capital = 0.0
    var rate = 0.0

    var profit: Double {
        get { 
            return capital + capital * rate
        }
        set(newProfit) {
            self.capital = newProfit / (1 + rate)
        }
    }

    convenience init(capital: Double, rate: Double) {     
     
        self.init()   
        self.capital = capital
        self.rate = rate
}


if you declare Account as a struct, you can call directly:

var myAcc = Account (capital: 1000.0, rate: 0.1)

Got it!


If I do not use the initializer, I should not pass arguments to it. Then, to change the values, I must directly access the properties.


var myAcc = Account ()
myAcc.capital = 100
myAcc.rate = 0.1


Thank so much!

Sorry for an unnecessary question. I did not notice at once that you wrote the same code to which I came a few minutes later))

Thanks!

Read Swift language reference manual ; there is a very clear explanation on initializers ; that will help you a lot to understand completely how this "magic" works.


And don't forget to close the thread.

close the thread of this topic? How?

Click "marked as correct" in the correct answer.