根据类的类型实现功能的类

问题描述 投票:0回答:1

我有一个通用类,需要根据通用类型返回一些数据。以下解决方案适用于具体的实现,不适用于诸如CaseIteratable之类的协议。有没有解决方法?即使在SomeThing内部,我也可以检查大小写是否可重复,但编译器不允许这样做

struct SomeThing<T>: DoSomething {
    let value: T

    func doSomething() {
        if let doable = value as? DoSomething {
            doable.doSomething()
        }
    }
}

protocol DoSomething {
    func doSomething()
}

extension Bool: DoSomething {
    func doSomething() {
        "bool action"
    }
}

// Won't compile
extension CaseIterable: DoSomething where Self: RawRepresentable {
    func doSomething() {
        "bool action"
    }
}

我也尝试为某些东西添加扩展名,但最终遇到相同的问题

extension SomeThing: DoSomething where T: Bool {}
extension SomeThing: DoSomething where T: CaseIteratable {}
swift
1个回答
0
投票

[定义协议扩展时,您可以指定约束一致的类型必须满足之前的方法和属性扩展名可用。您将这些约束写在通过编写泛型where子句扩展您要扩展的协议。对于有关泛型where子句的更多信息,请参见Generic Where Clauses

protocol extensions

struct SomeThing<T>: DoSomething { let value: T func doSomething() { if let doable = value as? DoSomething { doable.doSomething() } } } protocol DoSomething { func doSomething() } extension Bool: DoSomething { func doSomething() { "bool action" } } // this will compiles extension CaseIterable where Self: RawRepresentable, Self.RawValue == Bool { func doSomething() { "bool action" } } extension CaseIterable where Self: DoSomething {}

这是Github问题的另一个答案

这是因为出于一致性目的需要约束,否则,编译器会认为它是继承。

来源:Extension of protocol cannot have inheritance clause

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.