swift - Swift 将约束扩展添加到具有关联类型的协议
问题描述
当我向具有关联类型的协议添加约束扩展时,swift 编译器会忽略我的约束。
当我写:
protocol Arr {
associatedtype Element
func node(_ at: Int) -> Element?
}
extension Arr where Element == String {
func node(_ at: Int) -> String? {
nil
}
}
struct Doo: Arr {
}
Xcode 构建成功,它认为 myDoo
是. 它忽略了约束。Element
String
where Element == String
当我写:
protocol Arr {
associatedtype Element
func node(_ at: Int) -> Element?
}
extension Arr where Element == String {
func node(_ at: Int) -> Element? { // use Element
nil
}
}
struct Doo: Arr {
}
Xcode 按预期显示错误。
这是 Xcode 错误还是 Swift 功能?
Xcode 版本:Version 13.1 (13A1030d)
斯威夫特版本:
swift-driver version: 1.26.9 Apple Swift version 5.5.1 (swiftlang-1300.0.31.4 clang-1300.0.29.6)
Target: arm64-apple-macosx12.0
解决方案
出现第二种情况的错误是因为 Xcode 无法推断 Element 的类型。如果你指定它,一切都会编译。
struct Doo: Arr {
typealias Element = String
}
推荐阅读
- hybris - 将购物车送货地址分配给访客用户地址
- gatsby - 为什么 Gatsby 将 __gatsby_resolved 添加到我的一些 JSON 文件中?
- sql-server - 使用 bcp 在日期时间加载数据错误
- javascript - 将显示在数据库中的值插入不起作用
- python - 如何在 Python 中打印/返回矩阵中所有值的总和?
- php - 为什么 Laravel throw_unless 会给出内部服务器错误?
- javascript - 为什么 Javascript 计算这个方程的方式与我的计算器不同?
- javascript - 我无法从 React 事件侦听器上的函数更改变量
- visual-studio - 在 .NET Core 项目中使用 T4 模板时遇到问题
- clang-format - clang-format:将结构初始化保持在一行