【问题标题】:Why is function with protocol as its argument not working with type extensions that conform to the same protocol in Swift?为什么以协议为参数的函数不适用于符合 Swift 中相同协议的类型扩展?
【发布时间】:2019-10-21 17:11:26
【问题描述】:

我有一个协议 FnProtocolStringInt 符合该协议。

protocol FnProtocol {

}

extension Int: FnProtocol {

}

extension String: FnProtocol {

}

然后我创建了一个函数f3,它以FnProtocol 作为参数。

func f3(_ x: FnProtocol) -> FnProtocol {
    return x
}

接下来,comp 函数接受在 FnProtocol 上工作的函数数组。

func comp(fns: [(FnProtocol) -> FnProtocol]) -> (FnProtocol) -> FnProtocol {
    return fns[0]
}
func count(_ s: String) -> Int {
    return s.count
}

考虑到StringInt 符合FnProtocol,为什么comp(fns: [count]) 失败但comp(fns: [f3]) 有效?

comp(fns: [count])  // Cannot convert value of type '(String) -> Int' to expected element type '(FnProtocol) -> FnProtocol'

如何使用count 进行此操作?

【问题讨论】:

  • count 将 String 而不是 FnProtocol 作为参数,不知道为什么您希望隐式转换起作用?并且 s.count 仅适用于 String,不适用于 Int

标签: swift types swift-protocols


【解决方案1】:

为了能够使用count(),它需要将FnProtocol 作为参数

func count(_ s: FnProtocol) -> Int {
    return s.count
}

当然这意味着我们需要修改协议并让Int遵守它

protocol FnProtocol {
    var count: Int {get}
}

extension Int: FnProtocol {
    var count: Int {
        return String(self).count
    }
}

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多