繁体   English   中英

是否可以将 AnyClass 传递给泛型函数

[英]Is it possible to pass AnyClass to generic function

我试图将 AnyClass 传递给这样的通用函数:

if let arrayObjectClass = NSClassFromString("arrayObjectTypeName") {
    foo(type: arrayObjectClass)
}

foo看起来像这样:

func foo<T>(type: T.Type) {
    ...
}

但它无法编译并出现错误: Cannot convert value of type 'AnyClass' (aka 'AnyObject.Type') to expected argument type 'T.Type'

编译器需要一个类型为你的T那里。 您的AnyClass实例不是类型。 所以你的foo需要知道这个类应该是什么。 这必须在运行时完成。

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
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM