what happens if after guard let I return from init? I know that if it's a failable init(like init?) it returns nil.
init(_ quoteRequest: QuoteRequest?, buy: Bool = true) {
super.init(nibName: nil, bundle: nil)
guard let quoteRequest = quoteRequest else { return }
self.quoteRequest = quoteRequest
self.buy = buy
}
does object initializes? or partly? don't get it
I did't get any errors, but I don't understand what happend.
CodePudding user response:
If the code compiles, clearly your quoteRequest
and buy
do not need initialization. (They must already have a value, even if it is just nil.)
So the answer to your question is: initialization of your object succeeded and ended when you said super.init
.
Everything after that is just normal code. It runs or it doesn't, based on the guard statement, with no effect on actual initialization. Basically you are saying, okay, initialization is finished, now here's some addition optional stuff that you might do.
(It also occurs to me that this might more sense as a convenience initializer, since you are always calling the designated initializer anyway and you have no specialized designated-initializer work to do.)
CodePudding user response:
I guess self.buy
is either an optional Bool, or has a default value :
var buy: Bool?
// OR
var buy: Bool = true // or false
So what happens, is that if quoteRequest
is nil, the guard
instructions returns, so self.quoteRequest
and self.buy
are left unchanged (they do not take into account init
parameters).
And if quoteRequest
is not nil, then they are both initialized with constructor's parameters values.
It would be equivalent (but arguably worse) to write :
init(_ quoteRequest: QuoteRequest?, buy: Bool = true)
{
super.init(nibName: nil, bundle: nil)
if let quoteRequest = quoteRequest // quoteRequest != nil
{
self.quoteRequest = quoteRequest
self.buy = quoteRequest != nil ? buy : nil
}
}
CodePudding user response:
code below will never be executed!!!