Get App Name in Swift

后端 未结 17 2005
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 00:20

How do I get the application name in Swift?

Googling gave me this:

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


        
17条回答
  •  不知归路
    2020-12-24 00:55

    For swift 5, iOS 13*

    As mentioned before, it‘s an optional, so put it in a guard statement. I do this using a struct:

    struct Model {
        struct ProgVariablen{
            static var appBundleName:String {
                get {guard Bundle.main.infoDictionary != nil else {return ""}
                    return Bundle.main.infoDictionary!["CFBundleName"] as! String
                }//end get
            }//end computed property
            static var appBundleShortVersion:String {
                get {guard Bundle.main.infoDictionary != nil else {return ""}
                    return Bundle.main.infoDictionary ["CFBundleShortVersionString"] as! String
                }//end get
            }//end computed property
            static var appBundleBuild:String {
                get {guard Bundle.main.infoDictionary != nil else {return ""}
                    return Bundle.main.infoDictionary["CFBundleVersion"] as! String
            }//end get
        }//end computed property
    
        //initialsieren der Variablen
        init(
             appBundleName:String,
             appBundleShortVersion:String,
             appBundleBuild:String,
             )
        {
            // do here nothing for 'let'
            // do here nothing for 'computed properties'
            // your other ‘var’ are here like:
            // ProgVariablen.var1 = var1
        }//end init
        }//end struct ProgVariablen
    }//end struct Model
    

    Usage:

    print("Model.ProgVariablen.appBundleName: '\(Model.ProgVariablen.appBundleName)'")
    

提交回复
热议问题