swift - 为什么我可以用泛型在 swift 中提出相同类型的要求?有什么办法吗?

标签 swift generics

好的,所以我定义了一些这样的类:

public final class Process<InputType, OutputType, Memory>

而且我想让该函数仅适用于 InputType 和 OutputType 是完全相同的类型。 所以我像这样尝试过:

extension Process where InputType == OutputType { }

但这会导致:

Same-type requirement makes generic parameters InputType and OutputType equivalent

然后我走得有点远,并尝试这样做:

func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {}

但这会导致完全相同的错误。 所以问题是为什么我不能以两种泛型类型等效的方式定义泛型,因为这正是我想要的。我想定义仅适用于这种情况的函数,如果不遵守此规则,它将在编译时失败。

所以现在我正在使用这样的东西:

public static func bypass<SameType>() -> Process<SameType, SameType, Memory>

这最终只会在运行时失败,甚至不会在创建时失败,而是在触发具体类执行操作时失败。

有没有办法为相同类型的泛型参数定义extensionfunction 而不会编译(导致编译时错误)?

更新:遗漏了一些实现细节,因为这会使代码不可读,而且它们对上下文并不重要

最佳答案

Swift 4 及更高版本中,您可以这样写:

public final class Process<InputType, OutputType, Memory> {
    // ...
}

extension Process where InputType == OutputType {
    func bypass() -> Process<InputType, OutputType, Memory> {
        // ...
    }
}

原始答案(Swift 3):

即使some changes,你还不能限制泛型类的类型即将在 Swift 4 中出现。但是,您可以在协议(protocol)上约束类型。您可以创建一个只有 Process 符合的协议(protocol),如下所示:

protocol ProcessProtocol {
    // I haven't found a way to name these associated type identically to
    // those in the class. If anyone discover a way, please let me know
    associatedtype IT
    associatedtype OT
    associatedtype MT
}

final public class Process<InputType, OutputType, MemoryType>: ProcessProtocol {
    typealias IT = InputType
    typealias OT = OutputType
    typealias MT = MemoryType

    // your code
}

// Note that this is an extension on the protocol, not the class
extension ProcessProtocol where IT == OT {
    func foo() {
        // this function is only available when InputType = OutputType
    }
}

关于swift - 为什么我可以用泛型在 swift 中提出相同类型的要求?有什么办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941566/

相关文章:

c# - 通用类型列表

TypeScript:返回扩展 Record<string, string> 的通用类型的函数

java - 如何做泛型类 T 的 "new"扩展 AbstractClass (JAVA)

swift - 使用 Swift 显示 AVSpeechSynthesizer 显示为字幕的内容

iOS swift : AWS SDK - downloading file from S3 - get contents without saving file

ios - 获取不超过两个字母的日历工作日符号

java - 在 Java 中强制转换由通用实例类型的 getClass() 返回的类是否总是安全的?

Java 8 : Generic type inference improvements

swift - 使用通用协议(protocol)作为返回类型调用函数

ios - if let variable - 使用未解析的标识符