I have this class method and i'm calling this method in my view controller
class func initWithNewFrame(var frame : CGRect?)
{
if let newFrame = frame
{
var backgroundView : BackgroundView = BackgroundView(frame: newFrame)
}
}
I,m calling as
var frameNew : CGRect = CGRectMake(self.view.frame.origin.x,
self.view.frame.origin.y,
self.view.frame.size.width,
self.view.frame.size.height)
self.gradientView = BackgroundView.initWithNewFrame(frameNew)
and i got this error "0" is not convertible to BackgroundView in swift , Please solve this and thanks in advance.
Reason:
The error comes from here: self.gradientView = BackgroundView.initWithNewFrame(frameNew)
You assign self.gradientView
with return value of initWithNewFrame
, but in your code, initWithNewFrame
has no return value.
In Swift, no return value means return an empty tuple. So you got "“0” is not convertible to BackgroundView" error, because you want to assign a BackgroundView
with an empty tuple.
Maybe this is your expected method:
class func initWithNewFrame(var frame : CGRect?) -> BackgroundView?
{
var backgroundView : BackgroundView? = nil
if let newFrame = frame
{
backgroundView = BackgroundView(frame: newFrame)
}
return backgroundView
}
Update:
if you want to make a custom initializer for class BackgroundView
, try this:
convenience init(var frame : CGRect?) {
if let newFrame = frame
{
self.init(newFrame )
}
// Do custom thing
}