gpt4 book ai didi

swift - 将结构的 "type"作为参数在 Swift 中传递?

转载 作者:行者123 更新时间:2023-12-04 10:20:32 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to pass a Swift type as a method argument?

(1 个回答)


去年关闭。




是否可以将结构的“类型”作为参数传递?下面的用例(语法不起作用):

// Declarations.
public protocol Event {}

public enum AwesomeEvents {
public enum Notifications {
public struct NotificationReceived : Event {
...
}
}
}

// Is it possible to do something like this?
func testNotifications {
...
doSomethingAndCheckEventType(correctEventType: AwesomeEvents.Notifications.NotificationReceived.Type)
}

func doSomethingAndCheckEventType<T: Event>(correctEventType: T) {
...
XCTestAssertTrue(someEvent is correctEventType)
}

最佳答案

您可以使用 the == operator for metatypes .

func testNotifications() {
doSomethingAndCheckEventType(correctEventType: AwesomeEvents.Notifications.NotificationReceived.self)
}

func doSomethingAndCheckEventType<CorrectEvent: Event>(correctEventType: CorrectEvent.Type) {
let someEvent = AwesomeEvents.Notifications.NotificationReceived()
XCTAssert(type(of: someEvent) == correctEventType)
}

关于swift - 将结构的 "type"作为参数在 Swift 中传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875539/

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