2 Replies
      Latest reply: Sep 5, 2016 2:59 AM by eskimo RSS
      advancecoder56 Level 1 Level 1 (0 points)
                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?

        • Re: Two questions: Regarding NSTextField in Swift 2.2
          Claude31 Level 4 Level 4 (825 points)

          Your TextField view has probably a textField inside.

           

          That's what you need to set textField to.

          • Re: Two questions: Regarding NSTextField in Swift 2.2
            eskimo Apple Staff Apple Staff (6,310 points)

            In Objective-C -makeViewWithIdentifier:xxx 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"