首页 > 解决方案 > 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是. 它忽略了约束。ElementStringwhere 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

标签: swiftprotocolsassociated-types

解决方案


出现第二种情况的错误是因为 Xcode 无法推断 Element 的类型。如果你指定它,一切都会编译。

struct Doo: Arr {
    typealias Element = String
    
}

推荐阅读