在Swift中获取应用名称 [英] Get App Name in Swift
本文介绍了在Swift中获取应用名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Swift中获取应用程序名称?
How do I get the application name in Swift?
Google搜索给了我这个:
Googling gave me this:
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
我将其转换为Swift;错误-方法不存在:
I converted it to Swift; error - method doesn't exist:
NSBundle.mainBundle().infoDictionary.objectForKey("CFBundleName")
推荐答案
这应该有效:
NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
infoDictionary
被声明为 var infoDictionary:[NSObject:AnyObject]!
,因此您必须将其拆开,将其作为Swift字典进行访问(而不是使用 objectForKey
),然后将其转换为 AnyObject
,将其强制转换。
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.
更新Swift 3( Xcode 8 beta 2)
在可能的情况下也总是最好使用常量:
Always better to use constants where possible, too:
Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
这篇关于在Swift中获取应用名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文