swift - 协议扩展使用 where 子句在 Swift 中不起作用
问题描述
我们知道在 Swift 中,我们可以where
在协议扩展中使用子句:
protocol Ordered {
func precedes(other: Self) -> Bool
}
func binarySearch<T: Ordered>(sortedKeys: [T], forKey k: T) -> Int { 11 }
// I want make all Comparable types confirm Ordered protocol,but compiler complained later...
extension Ordered where Self: Comparable {
func precedes(other: Self) -> Bool {
return self < other
}
}
// ERROR: Global function 'binarySearch(sortedKeys:forKey:)' requires that 'Int' conform to 'Ordered'
let position = binarySearch(sortedKeys: [2, 3, 5, 7], forKey: 5)
因为 Int、String、Double 等都符合,所以我想对任意类型Comparable
的数组执行 binarySearch 。Comparable
但是上面的代码在编译的时候是错误的。那么如何解决呢?谢谢 ;)
解决方案
Adding :
extension Int: Ordered { }
will fix the compiler error but Ordered
is redundant with Comparable
. Why not just declaring :
func binarySearch<T: Comparable>(sortedKeys: [T], forKey k: T) -> Int { 11 }
?
推荐阅读
- javascript - 反应自定义钩子,计数器不断增加
- flutter - 如何滚动在颤动中组合的两个视图
- c++ - 从 main 调用类(单独的 cpp 文件)中定义的函数时,“标识符未定义”
- java - 将二进制转换为十六进制和十六进制转换为二进制
- node.js - 将网站部署到 Heroku 时出现应用程序错误
- node.js - 我们可以在 express 上添加 filter 由 pinoLogger 生成的 req 对象吗?就像它在使用 ddStream 登录到文件之前在 req 对象中显示 cookie
- docker - Travis CI - docker 镜像未推送到 dockerhub
- java - spring boot 无法在 mysql 中创建表
- c# - Powershell Net.WebRequest Timeout 不起作用
- docker - 支持在 docker 容器内运行 wireguard 的网络配置