gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:37 26 4
gpt4 key购买 nike

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

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

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

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

有人知道为什么会这样吗?

最佳答案

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

要实现这一点,您可能希望将此方法放在您的类型的扩展中,并使用您想要的 where 子句。例如

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

关于swift - 为什么 where 子句仅对具有泛型参数的函数有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com