Reputation: 3069
Im trying to pass AnyClass to generic function like this:
if let arrayObjectClass = NSClassFromString("arrayObjectTypeName") {
foo(type: arrayObjectClass)
}
where foo
looks like this:
func foo<T>(type: T.Type) {
...
}
but it fails to compile with error:
Cannot convert value of type 'AnyClass' (aka 'AnyObject.Type') to expected argument type 'T.Type'
Upvotes: 2
Views: 154
Reputation:
The compiler needs a type for your T
there. Your AnyClass
instance is not a type. So your foo
will need to know what the class is supposed to be. This must be done at runtime.
if let arrayObjectClass = NSClassFromString("arrayObjectTypeName") {
try foo(class: arrayObjectClass, arrayObjectTypeName.self)
}
func foo<T>(class: AnyClass, _: T.Type) throws {
if let error = CastError(`class`, desired: T.self)
{ throw error }
}
/// An error that represents casting gone wrong. 🧙♀️🙀
public enum CastError: Error {
/// An undesired cast is possible.
case possible
/// An desired cast is not possible.
case impossible
}
public extension CastError {
/// `nil` if an `Instance` can be cast to `Desired`. Otherwise, `.impossible`.
init?<Instance, Desired>(_: Instance, desired _: Desired.Type) {
self.init(Instance.self, desired: Desired.self)
}
/// `nil` if a `Source` can be cast to `Desired`. Otherwise, `.impossible`.
init?<Source, Desired>(_: Source.Type, desired _: Desired.Type) {
if Source.self is Desired.Type
{ return nil }
self = .impossible
}
/// `nil` if an `Instance` cannot be cast to `Undesired`. Otherwise, `.possible`.
init?<Instance, Undesired>(_: Instance, undesired _: Undesired.Type) {
self.init(Instance.self, undesired: Undesired.self)
}
/// `nil` if a `Source` cannot be cast to `Undesired`. Otherwise, `.possible`.
init?<Source, Undesired>(_: Source.Type, undesired _: Undesired.Type) {
guard Source.self is Undesired.Type
else { return nil }
self = .possible
}
}
Upvotes: 2