0
votes

I was having tons of problems with Swift when subclassing anything in Cocoa, so I decided to create an MVCE and post it on here. Try it out yourself.

I created a simple Cocoa application in Xcode with the following options:

Language: Swift
Use Storyboards: No

I then created a subclass of NSView named Rectangle:

import Foundation
import Cocoa

class Rectangle: NSView {                //1
    init(frame: NSRect) {                //2
        super.init(frame: frame)         //3
    }                                    //4
}                                        //5

What's strange is that some of errors come and go while I type. When I compile the project, I get the following errors:

//2: Overriding declaration requires an 'override keyword'
//5: 'required' initializer 'init(coder:)' must be provided by subclass of 'NSView'

As soon as I start typing, I get the following additional errors:

//1: Use of undeclared type 'NSView'
//3: 'super' members cannot be referenced in a root class

If I compile again, the two previous errors disappear.

Any idea what I'm doing wrong? Like I said, try it out yourself. Maybe it's a bug.

1

1 Answers

0
votes

It doesn't sound like you are doing anything wrong, other than forgetting the override keyword and forgetting to implement the initWithCoder method.

Remember, as you are typing, the code is in an unstable state. When you start writing a line of code, it will be full of errors until you are done writing it.