如何在 flatMap 中使用 swift 实例方法?

How to use a swift Instance method with flatMap?

我可以定义一个将字符串加倍的全局函数:

func double(string: String) -> [String] {
  return [string, string]
}

现在可以将其与 flatMap 一起使用

let animals = ["Ant", "Bear", "Cat"]
print( animals.flatMap(double) ) // ["Ant", "Ant", "Bear", "Bear", "Cat", "Cat"]

但我们不喜欢 Globals ;-) 所以我改为扩展字符串:

extension String {
  func double() -> [String] {
    return [self, self]
  }
}

但我不能像我得到的那样使用它:

print( animals.flatMap(String.double) ) // [(Function), (Function), (Function)]

我可以看出问题是类型不同。

print("type(of: double) = \(type(of: double))") //type(of: double) = (String) -> Array<String>
print("type(of: String.double) = \(type(of: String.double))") //type(of: String.double) = (String) -> () -> Array<String>

我可以看到 String.double 不是 flatMap 的正确类型,我收到的警告消息强调了这一点:

'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value

我认为这是因为编译器没有为 flatMap 找到合适的重载。

如何像使用全局函数一样使用 flatMap 的实例方法?

使用实例方法,你不能。

实例方法是curry方法,类型(String) -> () -> Array<String>表示"a method take string and return a function which takes nothing and return array of string"。

所以你可以这样做,但不是你写的那样。

print(animals.flatMap{ String.double([=10=])() }) // ["Ant", "Ant", "Bear", "Bear", "Cat", "Cat"]

你需要的是静态方法。它只需要字符串和 return 字符串数组。

extension String {
    static func double(_ string: String) -> [String] {
        return [string, string]
    }
}

print(animals.flatMap(String.double)) // ["Ant", "Ant", "Bear", "Bear", "Cat", "Cat"]