How to provide a default value for a metatype parameter in a Swift function?

48 Views Asked by At

In my app, I often need to access values stored in Info.plist. Instead of typing things like Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String every time, I created a nice wrapper.

The method for accessing values in Info.plist is declared like this:

static func get<T>(_ name: String, as type: T.Type) -> T? {
    return Bundle.main.infoDictionary?[name] as? T
}

It works fine when called like that:

let appID = IPWrapper.get("APP_ID", as: String.self)

However, specifying the type every time is tiresome since many values in Info.plist are of type String). That’s why I’d like to provide a default value for the type parameter so I can omit it.

Unfortunately, the usual method of providing default values (adding = default_value in function declaration) doesn’t work: Xcode throws an error that says “Default argument value of type 'String.Type' cannot be converted to type 'T.Type'”.

// This code doesn’t work.
static func get<T>(_ name: String, as type: T.Type = String.self) -> T? { … }

Am I doing something wrong?

UPD: Looks like overloading is the only way to fix this.

static func get<T>(_ name: String, as type: T.Type) -> T? {
    return Bundle.main.infoDictionary?[name] as? T
}

static func get(_ name: String) -> String? {
    return get(name, as: String.self)
}
0

There are 0 best solutions below