I have a swift function to get the localized app name from the main bundle's localizedInfoDictionary
with some fallback cases.
private func defaultAppName() -> String {
var name: NSString = ""
// Check for a localized version of the CFBundleDisplayName
var mainBundle = NSBundle.mainBundle()
// EXC_BAD_ACCESS HERE, despite the optional
var mainBundleInfoDictionary: Dictionary<NSObject, AnyObject>? = mainBundle.localizedInfoDictionary
if let infoDictionary = mainBundleInfoDictionary {
name = infoDictionary["CFBundleDisplayName"] as NSString
if (name.length == 0) {
name = infoDictionary[kCFBundleNameKey] as NSString
}
}
if (name.length == 0) {
mainBundleInfoDictionary = mainBundle.infoDictionary
if let infoDictionary = mainBundleInfoDictionary {
name = infoDictionary["CFBundleDisplayName"] as NSString
if (name.length == 0) {
name = infoDictionary[kCFBundleNameKey] as NSString
}
}
}
return name
}
I know it's not concise, but I am still learning swift. The problem I am seeing is that accessing mainBundle.localizedInfoDictionary
is not returning nil when not found, but rather throwing an EXC_BAD_ACCESS
. I cannot guarantee that there will be a localized info in the apps where this function is used, yet the standard swift way of handling optionals is not working here.
How can I either catch the exception thrown by NSBundle's localizedInfoDictionary
call or adapt my swift code to move on?