Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override multiple overloaded init() methods in Swift

Tags:

swift

I'm attempting to create a custom NSTextFieldCell subclass in Swift (Xcode Beta 5), with the following code:

class CustomHighlightTextFieldCell : NSTextFieldCell {

    required init(coder aCoder: NSCoder!) {
        super.init(coder: aCoder)
    }

    init(imageCell anImage: NSImage!) {
        super.init(imageCell: anImage)
    }

    init(textCell aString: String!) {
        super.init(textCell: aString)
    }
}

However, I receive compilation errors on the 2nd and 3rd init() declarations:

/Users/Craig/projects/.../CustomHighlightTextFieldCell:8:40: Invalid redeclaration of 'init(imageCell:)'
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:5: 'init(imageCell:)' previously declared here

/Users/Craig/projects/.../CustomHighlightTextFieldCell:7:39: Invalid redeclaration of 'init(textCell:)'
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:5: 'init(textCell:)' previously declared here

While there are some strange compiler bugs here (I'm getting the usual "SourceKitService Terminated, Editor functionality temporarily limited." message), it seems like I'm missing something in my method overriding - but I can't tell what.

I was under the assumption the named parameters, or at least the parameter types, would indicate that there are three different init() methods here, but apparently I'm missing a key piece of the puzzle.

Edit: If I add override to the 2nd and 3rd init() methods, I have a separate issue:

required init(coder aCoder: NSCoder!) {
    super.init(coder: aCoder)
}

override init(imageCell anImage: NSImage!) {
    super.init(imageCell: anImage)
}

override init(textCell aString: String!) {
    super.init(textCell: aString)
}

This new issue (simply invoked by adding the two override keywords) seems to almost contradict the original.

/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:14: Initializer does not override a designated initializer from its superclass
/Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:14: Initializer does not override a designated initializer from its superclass
like image 784
Craig Otis Avatar asked Feb 12 '23 07:02

Craig Otis


1 Answers

It would seem that your declarations (with override) should be sufficient, however, they seem to need the @objc declarations as well. This works:

class CustomHighlightTextFieldCell : NSTextFieldCell {

    required init(coder aCoder: NSCoder!) {
        super.init(coder: aCoder)
    }

    @objc(initImageCell:)
    override init(imageCell anImage: NSImage!) {
        super.init(imageCell: anImage)
    }

    @objc(initTextCell:)
    override init(textCell aString: String!) {
        super.init(textCell: aString)
    }
}
like image 187
Grimxn Avatar answered Mar 15 '23 14:03

Grimxn