I have a custom NSView Class that looks like:
class MyClass: NSView
{
var myClassVar: NSColor
}
Naturally, Xcode is complaining that my class has no initializers, so I need to override the designated initializer so I can initialize myClassVar.
How can I do this?
Try this;
class MyClass: NSView
{
var myClassVar: NSColor! // the optional mark ! to be noticed.
override init(frame frameRect: NSRect) {
super.init(frame:frameRect);
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
//or customized constructor/ init
init(frame frameRect: NSRect, otherInfo:Int) {
super.init(frame:frameRect);
// other code
}
}
If you give your color a default value, the initializers from NSView should still work.
Here are several ways to do this:
var myClassVar: NSColor?
var myClassVar: NSColor! // make sure to set this before you actually access it
var myClassVar: NSColor = NSColor.clearColor()
The second example (implicitly unwrapped optional) is what Apple does with IBOutlets. Otherwise you would need to have an initializer that sets each of your variables to a non-null value in your init methods.
For more information about this, see Swift Initialization and the Pain of Optionals , which discusses these solutions:
NSColor?
), instantiating it after super.init NSColor!
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.