我有一个需求,其中我有多个符合protocolP的struct,稍后我通过Computer struct 收集并执行像compute()这样的方法,这有助于创建每个符合类型的实例

为什么以下代码不能运行,需要进行哪些更改才能运行:

import Foundation

protocol P {
    static func instance() -> Self
}

struct A: P {
    static func instance() -> A {
        A()
    }
}

struct B: P {
    static func instance() -> B {
        B()
    }
}

struct Computer<T: P> {
    
    static func compute() -> T {
        T.instance()
    }
}

let someArray: [P.Type] = [
    A.self,
    B.self
]

for value in someArray {
    Computer<value>.compute() // ERROR: Cannot find type 'value' in scope
}

推荐答案

如果将类型作为变量传递给compute,则不需要泛型约束:

struct Computer {
    static func compute(with anyP: P.Type) -> P {
        anyP.instance()
    }
}

或者,如果得到的compute类型不应显式为P,则可以将泛型约束放入方法中:

struct Computer {
    static func compute<T: P>(with anyP: T.Type) -> T {
        anyP.instance()
    }
}

然后像这样拨打compute:

for value in someArray {
    let instance = Computer.compute(with: value)
    instance.doSomething()
}

这假设P具有方法doSomething.如果要访问特定于A的方法,则需要键入CAST.最后,instance对于编译器来说始终是P,因为它必须假设对someArray(即P.Type)内的任何值都将执行相同的代码.无论compute返回P,还是显式返回T,如果您像这样把它放在循环中,instance仍然会被推断为P.

Ios相关问答推荐

如何在react 本机模块中使用Bundle.main.Path()在SWIFT中导入assets资源

将数据传回VC时委托为空

OnTapGesture在其修改的视图外部触发

如何在SwiftUI中基于嵌套视图中的状态动态显示外部视图的内容?

在flutter中使用flatter_screenutil这样的软件包的目的是什么?

在 iOS 上以后台模式安排任务(屏幕时间 API)

当 .searchable 修饰符处于活动状态时,如何将变量设置为 false?

占位符文本未显示在 TextEditor 上

如何为 XCTest、SwiftUI 预览等初始化带有 @MainActor 注释的 Swift 类

滚动 swiftUI 列表时,未调用单元格的任务修饰符.怎么修?

视图之间的 SwiftUI 过渡,没有过渡

转换在 NavigationView 中不起作用

在使用 Github Actions 时,我面临权限被拒绝错误

如何在 Swift 上的 sendSynchronousRequest 中判断 Response.statusCode

iPhone 6 和 6 Plus 媒体查询

如何找出坐标之间的距离?

在 Swift 中将 HTML 转换为纯文本

iOS 中的 Crashlytics 不会继续通过 Fabric 应用程序中的构建您的项目

AVAudioRecorder 抛出错误

Info.plist 实用程序错误:无法打开 Info.plist,因为没有这样的文件