为什么 where 子句只对具有泛型参数的函数有效?

Sid*_*ani 5 generics swift

这个方法签名不能在 Swift 4 中编译似乎很荒谬:

class Bar<ValueType> { 
    func version() throws -> String where ValueType == [String: Any] { ... }
}   
Run Code Online (Sandbox Code Playgroud)

(错误:where 子句不能附加到非泛型声明)
但这编译得很好:

class Bar<ValueType> { 
   func version<T>(_ foo: T? = nil) throws -> String where ValueType == [String: Any] { ... }  
} 
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么会这样?

Ale*_*ica 3

因为ValueType与此方法无关(在第一个示例中)。将这样的方法放入类型 ( class// struct)中是错误的enum,因为它实际上并不是该类型的真正成员。它有条件地成为该类型的成员,具体取决于子句的真值where

为了实现这一点,您需要将此方法与where您想要的子句一起放入您的类型的扩展中。例如

extension YourType where ValueType == [String: Any] {
    func version() throws -> String { ... }
}
Run Code Online (Sandbox Code Playgroud)