gpt4 book ai didi

swift - Swift 2.2+ 中类型的上下文类型推断

转载 作者:行者123 更新时间:2023-11-28 06:42:47 25 4
gpt4 key购买 nike

我想在 Swift 中使用一阶公民类型来决定调用哪个函数。

func sf(v: [Float]) -> Float{
}

func df(v: [Double]) -> Double {
}

func f<T: RealType>(seq ls: [T]) -> T {
if T.self == Float.self {
return sf(ls) // 1. where sf: Float -> Void
} else if T.self == Double.self {
return df(ls) // 2. where df : Double -> Void
}
}

类型推断系统无法注意到在一个分支下 T == Float 和另一个分支下的 Double ?

这是缺失的功能、复杂的功能还是错误?

编辑:

typealias RealType = protocol<FloatingPointType, Hashable, Equatable, Comparable, FloatLiteralConvertible, SignedNumberType> 

用于我的原型(prototype)但将成为协议(protocol)

最佳答案

您正试图将泛型给出的静态解析与运行时决策结合起来,这是不可能的。

您可以简单地为 FloatDouble 重载 f 以获得您需要的:

func f(seq ls: [Float]) -> Float {
return sf(ls) // 1. where sf: Float -> Void
}

func f(seq ls: [Double]) -> Double {
return df(ls) // 2. where df : Double -> Void
}

但是,如果您希望 RealType 成为一个通用占位符,您可以在除 FloatDouble 之外的其他类型上使用,那么您可以做这样的事情:

protocol RealType {
static func processArray(v: [Self]) -> Self
}

extension Float: RealType {
static func processArray(v: [Float]) -> Float {
return sf(v)
}
}

extension Double: RealType {
static func processArray(v: [Double]) -> Double {
return df(v)
}
}

func sf(v: [Float]) -> Float{
return 0
}

func df(v: [Double]) -> Double {
return 0
}

func f<T: RealType>(seq ls: [T]) -> T {
return T.processArray(ls)
}

这将为您提供类型安全(这是 Swift 的主要优势之一)和可扩展性,因为无论何时您需要在另一种类型上添加对 f 的支持,您只需要将该类型声明为符合为 RealType,并实现 processArray 方法。

关于swift - Swift 2.2+ 中类型的上下文类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467654/

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