N3v1
N3v1

Reputation: 53

Type of expression is ambiguous without a type annotation

I'm getting a 'Type of expression is ambiguous with a type annotation' error. I'm using the latest beta version of Xcode and Swift. I can't seem to figure it out. I tried different things but can't get it to work. The problem is on the syntax of this line

if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String {
   return build
}

Here's my full code:

extension Bundle {
    class var applicationVersionNumber: String {
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] {
            var applicationBuildNumber: String {
                if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String {
                    return build
                }
                return "Build Number Not Available"
            }
        }
    }
}

struct SLInfoView: View {
    let versionNumber = Bundle.applicationVersionNumber
    var body: some View {
        NavigationStack {
            List {
                Section() {
                    HStack {
                        Text("Version")
                        Spacer()
                        Text(versionNumber)
                    }
                } header: {
                    Text("General infos")
                } footer: {
                    Text("")
                }
            }
                .navigationTitle("Info")
                .navigationBarTitleDisplayMode(.inline)
        }
    }
}

#Preview {
    SLInfoView()
}

I want to get the version number from my application to show my version and build number in a SwiftUI View. I'd be really grateful if someone could help me. Is this the right way to do it?

Upvotes: 3

Views: 16376

Answers (1)

HangarRash
HangarRash

Reputation: 15038

  1. It seems you somehow copied and pasted a computed property inside another computed property.
  2. You are needlessly using Bundle and NSBundle. Just use Bundle.
  3. Your applicationVersionNumber property should not be a class property. This lets you use the property on any bundle, not just the main bundle.
  4. Your property should return an optional so the caller can decide how to deal with the version not being available.

Here's the fixed extension:

extension Bundle {
    var applicationVersionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }

    var applicationBuildNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }
}

And the updated caller:

let versionNumber = Bundle.main.applicationVersionNumber ?? "Version Number Not Available"

Upvotes: 4

Related Questions