11

I'm trying to rewrite the following code from the Status Bar Programming Topics in Swift.

NSStatusBar *bar = [NSStatusBar systemStatusBar];

theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
[theItem retain];

[theItem setTitle: NSLocalizedString(@"Tablet",@"")];
...

My Swift code so far:

let bar = NSStatusBar.systemStatusBar()

let sm = bar.statusItemWithLength(NSVariableStatusItemLength)
sm.title = "Tablet"
...

The problem is that the statusItemWithLength method in Swift excepts CGFloat but NSVariableStatusItemLength is defined as CInt in Swift. I see the following error:

'CInt' is not convertible to 'CGFloat'

Definition in Xcode:

var NSVariableStatusItemLength: CInt { get }
var NSSquareStatusItemLength: CInt { get }

class NSStatusBar : NSObject {

    class func systemStatusBar() -> NSStatusBar!

    func statusItemWithLength(length: CGFloat) -> NSStatusItem!
    ...
}

Am I doing something wrong? How can I fix this?

2 Answers 2

27

For Beta 1 & 2 you can manually convert NSVariableStatusItemLength from CInt to the required CGFloat like so:

let sm = bar.statusItemWithLength( CGFloat(NSVariableStatusItemLength) )

In Beta 3 NSVariableStatusItemLength is now a CGFloat, but due to a linker error (bug) you have to use
-1 instead of NSVariableStatusItemLength and
-2 instead of NSSquareStatusItemLength

let sm = bar.statusItemWithLength( -1 )

Thanks to suzhi and gui_dos for figuring this out!

6
  • Thanks, this works. But basically it is somehow odd that a enum has wrong type...
    – idmean
    Jun 4, 2014 at 12:29
  • 3
    This solution stopped working for me as of Beta 6, with build error Undefined symbols for architecture x86_64: "_NSSquareStatusItemLength".
    – Greg W
    Jul 8, 2014 at 2:39
  • 1
    I have the same problem with beta 3 and I am stuck.
    – suzhi
    Jul 9, 2014 at 17:36
  • 4
    I found this: devforums.apple.com/message/1001121#1001121 Using "-1" oder "-2" is a workaround for now.
    – suzhi
    Jul 9, 2014 at 17:40
  • 1
    On 10.11 Beta and Xcode 7.0 beta 4 NSVariableStatusItemLength is available and there's no more link error.
    – James Chen
    Jul 26, 2015 at 4:31
2

As a workaround, with the Beta 3 release you can pass the Int constant directly. For instance:

statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength

https://github.com/gui-dos/Guigna/blob/181f9db1056dece888dc29424cc2da79f8f284e3/Guigna-Swift/Guigna/GuignaAppDelegate.swift#L138

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.