【发布时间】:2019-10-21 17:11:26
【问题描述】:
我有一个协议 FnProtocol,String 和 Int 符合该协议。
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
}
考虑到String 和Int 符合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