使用 resultBuilder 时,buildEither 中的类型推断是否可用于确定类型参数?

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

是否要求

buildEither(first:)
buildEither(second:)
返回相同的类型?我正在试验 resultBuilders,但无法推断出函数是如何转换的。

为了说明我的意思,我试图让

TwoTypes
初始化程序打印出两种 不同 类型。我试图让
if-else
语句确定
A
B
的类型,并打印这些类型:

struct TwoTypes<A, B> {
    init(a: A.Type, b: B.Type) {
        print(a)  
        print(b)
    }
}

@resultBuilder
struct TwoTypesBuilder<A, B> {
    // From the example below, I expected type-inference to determine "A" to be "Int"
    static func buildBlock(_ component: A) -> A {
        return component
    }
    static func buildEither(first component: A) -> A {
        return component
    }

    // From the example below, I expected type-inference to determine "B" to be "Double"
    static func buildBlock(_ component: B) -> B {
        return component
    }
    static func buildEither(second component: B) -> B {
        return component
    }

    // Since type-inference now knows A and B, we can print "Int" and "Double"
    // "T" represents *either* A or B
    static func buildFinalResult<T>(_ component: T) -> TwoTypes<A, B> {
        TwoTypes(a: A.self, b: B.self)
    }
}

func TwoTypesMake<A, B>(@TwoTypesBuilder<A, B> builder: () -> TwoTypes<A, B>) {
    builder()
}

func main() {
    TwoTypesMake {
        // This if-else statement would determine A and B, and thus, print out A.type and B.type in the 
        // TwoTypes initialiser 
        if Bool.random() {
            2  // << Error: Cannot convert value of type 'Int' to expected argument type 'Double'
        } else {
            3.4  // Error: Cannot convert value of type 'Double' to expected argument type 'Int'
        }
    }
}

main()

根据我对resultBuilders的理解,我认为这是不可能实现的(因此回复中简单的“不可能”就足够了)因为

vMerged
的类型(在result builders的提案中描述)不能确定。但是,我很想被证明是错误的,因为也许有一种方法可以让
vMerged
拥有占位符/泛型类型并在运行时初始化。

是否有可能以某种方式让

TwoTypes
初始化程序打印出两个不同的值?更具体地说,每个分支是否有可能产生不同的值并让类型推断确定每种类型,从而确定
A
B


对于那些懒得从结果生成器提案中找出

vMerged
是什么的人的小片段:

  • 如果结果构建器类型声明了
    buildEither(first:)
    buildEither(second:)
    结果构建方法,则选择具有 N 叶子的完整二叉树(注入树),并且每个产生结果的案例都被唯一地分配一个叶子在里面;这些决定是实现定义的。在语句之前声明了一个新类型的唯一变量
    vMerged

(不知道“新鲜型”是什么意思)

ios swift generics implementation builder
© www.soinside.com 2019 - 2024. All rights reserved.