For me, this has been e.g. for APICall<T>
- a base "abstract" class for API calls that return various values. I needed to track ongoing API calls, etc., so I needed an array of [APICall]
. Yeah, sure, you can create a protocol a work around that this way, but I've ended up (for various reasons) creating a APICallBase
that is not generic and contains some basic common implementation. I believe I've done so in one or two more cases that I have a non-generic Base
class to work around this.
As per the topic itself, I've found the following usecase:
class Preferences {
struct Key<T>: RawRepresentable {
var rawValue: String
}
func bool(for key: Key<Bool>) -> Bool { ... }
func value<T>(for key: Key<T>) -> T? { ... }
func value<T>(for key: Key<T>, defaultValue: T) -> T { ... }
}
This is a class representing typed preferences. The ideal usage would be something like this:
extension Preferences.Key {
static let myCoolPreference = Key<Bool>(rawValue: "MyCoolPreference")
}
extension Preferences {
var isMyCoolPreferenceEnabled: Bool {
get { return self.bool(for: .myCoolPreference) }
set { ... }
}
}
What's currently impossible is to create the extension of Key
and then address it with the short style .myCoolPreference
. Maybe I'm missing something, but something like this would create nice and type-safe preferences wrappers. You can nowadays declare various constants for accessing defaults, but they are untyped.
Of course, there is a workaround:
class Preferences {
// Untyped
struct Key: RawRepresentable {
var rawValue: String
}
// Typed
struct TypedKey<T>: RawRepresentable {
var rawValue: String
}
func bool(for key: TypedKey<Bool>) -> Bool { ... }
func value<T>(for key: TypedKey<T>) -> T? { ... }
func value<T>(for key: TypedKey<T>, defaultValue: T) -> T { ... }
}
Then you declare the static let
on the untyped Key
and address it as self.bool(for: Key.myCoolPreference)
. Works, but isn't a nice solution.