为什么以协议为参数的函数不能使用符合 Swift 中相同协议的类型扩展?
Why is function with protocol as its argument not working with type extensions that conform to the same protocol in Swift?
我有一个协议 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()
它需要将 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
}
}
我有一个协议 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()
它需要将 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
}
}