Search code examples
cocoaswift

Get App Name in Swift


How do I get the application name in Swift?

Googling gave me this:

[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];

I converted it to Swift; error - method doesn't exist:

NSBundle.mainBundle().infoDictionary.objectForKey("CFBundleName")

Solution

  • This should work:

    NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
    

    infoDictionary is declared as a var infoDictionary: [NSObject : AnyObject]! so you have to unwrap it, access it as a Swift dictionary (rather than use objectForKey), and, as the result is an AnyObject, cast it.

    Update Swift 3 (Xcode 8 beta 2)

    Always better to use constants (and optionals) where possible, too:

    Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String