gpt4 book ai didi

swift - 我必须沮丧还是我错过了什么?

转载 作者:行者123 更新时间:2023-12-03 18:48:57 24 4
gpt4 key购买 nike

所以我有一个我想在调用站点动态化的类型:

    struct DynamicView<Content: View>: View {
let content: Content
var body: some View {
content
}
}
使用某种类型的函数将其转换为具体的东西
    static func contentCreator<T: View>(id: Int) -> T {
switch id {
case 0:
return FirstView() //<-- Xcode is demanding that I state as! T here
}
}
FirstView 在哪里
struct FirstView: View {
var body: some View {
Circle()
}
}
我是在接近这个错误还是什么?只要它们都符合通用协议(protocol),它们应该是可以互换的,对吧?

最佳答案

这是因为类型不是通过检查返回来推断的。
如果你试试:

let v = contentCreator(id: 0)
你会得到一个 Generic parameter T could not be inferred错误,因为 v 类型未知。
如果设置了类型,它将编译:
let v: View = contentCreator(id: 0)
所以回到你的提问,因为 View 是一个协议(protocol),当 Xcode 构建源代码时,它无法知道类 'T',也没有办法在你使用它时强制你使用正确的类型。
struct FirstView: View {
var body: some View {
Circle()
}
}

struct SecondView: View {
var body: some View {
Square()
}
}

// This will work, because once executed, we know v1 class.
// The cast will work as long as v1 is declared as conforming to 'View' protocol.
// Type is not inferred in this case, but known only when it returns.

let v1: View = contentCreator(0)

/// This won't work, because the inferred type is 'SecondView'.
/// The cast 'return FirstView() as! T' will crash

let v2: SecondView = contentCreator(0)

关于swift - 我必须沮丧还是我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67270226/

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