在Swift中使用类型名称的通用函数

问题描述 投票:19回答:2

在C#中,可以通过指定类型来调用泛型方法:

public T f<T>()
{
   return something as T
}

var x = f<string>()

Swift不允许您在调用它时专门化泛型方法。编译器希望依赖类型推断,因此这是不可能的:

func f<T>() -> T? {
    return something as T?
}

let x = f<String>() // not allowed in Swift

我需要的是一种将类型传递给函数的方法,以及使用泛型返回该类型的对象的函数

这有效,但它不适合我想做的事情:

let x = f() as String?

编辑(澄清)

我可能不太清楚这个问题实际上是什么,它是关于调用返回给定类型(任何类型)的函数的更简单的语法。

举个简单的例子,假设您有一个Any数组,并创建一个返回给定类型的第一个元素的函数:

// returns the first element in the array of that type
func findFirst<T>(array: [Any]) -> T? {
    return array.filter() { $0 is T }.first as? T
}

您可以像这样调用此函数:

let array = [something,something,something,...]

let x = findFirst(array) as String?

这很简单,但是如果返回的类型是带有方法的某个协议并且您想要在返回的对象上调用该方法,那该怎么办:

(findFirst(array) as MyProtocol?)?.SomeMethodInMyProtocol()
(findFirst(array) as OtherProtocol?)?.SomeMethodInOtherProtocol()

这种语法很尴尬。在C#(与Swift一样强类型)中,您可以这样做:

findFirst<MyProtocol>(array).SomeMethodInMyProtocol();

可悲的是,这在Swift中是不可能的。

所以问题是:有没有办法用更清晰(不那么笨拙)的语法来实现这一点。

swift generics swift2
2个回答
31
投票

不幸的是,您无法明确定义泛型函数的类型(通过使用<...>语法)。但是,您可以提供一个通用元类型(T.Type)作为函数的参数,以便允许Swift推断函数的泛型类型,如Roman has said

对于您的具体示例,您希望您的函数看起来像这样:

func findFirst<T>(in array: [Any], ofType _: T.Type) -> T? {
  return array.lazy.compactMap { $0 as? T }.first
}

这里我们使用compactMap(_:)来获得成功地转换为T的元素序列,然后使用first来获得该序列的第一个元素。我们也使用lazy,以便我们可以在找到第一个后停止评估元素。

用法示例:

protocol SomeProtocol {
  func doSomething()
}

protocol AnotherProtocol {
  func somethingElse()
}

extension String : SomeProtocol {
  func doSomething() {
    print("success:", self)
  }
}

let a: [Any] = [5, "str", 6.7]

// Outputs "success: str", as the second element is castable to SomeProtocol.
findFirst(in: a, ofType: SomeProtocol.self)?.doSomething()

// Doesn't output anything, as none of the elements conform to AnotherProtocol.
findFirst(in: a, ofType: AnotherProtocol.self)?.somethingElse()

请注意,您必须使用.self才能引用特定类型的元类型(在本例中为SomeProtocol)。也许不像你想要的语法那样光滑,但我认为它与你将获得的一样好。

虽然在这种情况下值得注意的是,该函数将更好地放在Sequence的扩展中:

extension Sequence {
  func first<T>(ofType _: T.Type) -> T? {
    // Unfortunately we can't easily use lazy.compactMap { $0 as? T }.first
    // here, as LazyMapSequence doesn't have a 'first' property (we'd have to
    // get the iterator and call next(), but at that point we might as well
    // do a for loop)
    for element in self {
      if let element = element as? T {
        return element
      }
    }
    return nil
  }
}

let a: [Any] = [5, "str", 6.7]
print(a.first(ofType: String.self) as Any) // Optional("str")

3
投票

您可能需要做的是创建一个如下所示的协议:

protocol SomeProtocol {
    init()
    func someProtocolMethod()
}

然后在方法中添加T.Type作为参数:

func f<T: SomeProtocol>(t: T.Type) -> T {
    return T()
}

然后假设你有一个类似于SomeProtocol的类型:

struct MyType: SomeProtocol {
    init() { }
    func someProtocolMethod() { }
}

然后你可以这样调用你的函数:

f(MyType.self).someProtocolMethod()

像其他人一样,这似乎是一种令人费解的方式来做你想做的事情。例如,如果你知道类型,你可以写:

MyType().someProtocolMethod()

没有必要f

© www.soinside.com 2019 - 2024. All rights reserved.