用于检测可选关联类型的 Swift 泛型

标签 swift generics

<分区>

如何将扩展限制为仅在关联类型为可选时才匹配?

例如:

protocol FooProtocol: class {
    associatedtype BarType
    var contents: BarType { get }
}

extension FooProtocol where BarType: Optional<Any> {
    func unwrap() -> BarType {
        return self.contents!
    }
}

class BazClass: FooProtocol {
    typealias BarType = String?
    var contents: BarType
}

此错误与 Type 'Self.BarType' constrained to non-protocol type 'Optional<Any>'在扩展的左括号上。我也试过 Any? , BarType?代替 Optional<Any> .最后一个错误 Inheritance from non-named type 'BarType?'相反。

最佳答案

String 和 Optional 是值类型,不是协议(protocol)。这就是为什么你不能说 BarType: Optional<String> ,因为没有任何东西可以从中继承。

您可以使用相同类型的约束 (但这仅在 Swift 4 中可行) 似乎也适用于 Swift 3.1:

extension FooProtocol where BarType == String? {
    // ...
}

关于用于检测可选关联类型的 Swift 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44550471/

相关文章:

ios - 单击按钮线程 1 后出现错误 : Signal SIGABRT

swift - 通过搜索栏创建到另一个 View Controller 的 segue?

swift - Swift 中的字符串操作

swift - 以编程方式访问 macOS Mojave 中的 safari 书签

C#:如何设计一个泛型类,使得类型参数必须继承某个类?

C# 如何创建泛型类?

swift - 倒数计时器将不起作用,因为它不接受本地功能

Java:如何在 SomeClass<T> 中为 "T"设置默认值?

generics - 为什么 Dart 泛型类不能根据构造函数确定其类型