Two questions: Regarding NSTextField in Swift 2.2

        var textField: NSTextField = tableView.makeViewWithIdentifier("TextField", owner: self)


gives the following error:


Cannot convert value of type 'NSView?' to specified type 'NSTextField'


while in Objective-C, the following call works and doesn't cause any errors in Xcode 7+.


What should I do?


Also, I have the following line of code:


      if (textField == nil) {


gives the following error:


Value of type 'NSTextField' can never be nil, comparison isn't allowed.


while Objective-C, the following statement works and doesn't cause any errors in Xcode 7+.


What should I do?

Replies

Your TextField view has probably a textField inside.


That's what you need to set textField to.

In Objective-C

-makeViewWithIdentifier:***
is declared like this:
- (nullable __kindof NSView *)makeViewWithIdentifier:…

This allows you to assign the result to an NSView or any NSView subclass without a warning. This isn’t imported into Swift with 100% fidelity. Instead you get this:

public func makeViewWithIdentifier(…) -> NSView?

which is only compatible with NSView itself. To fix this you have to cast the result:

let textField: NSTextField = tableView.makeViewWithIdentifier("TextField", owner: self) as! NSTextField

This will trap at runtime if the value is nil or not an NSTextField or subclass thereof, but that’s probably a good thing (-:

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"