gpt4 book ai didi

swift - 泛型函数参数默认值

转载 作者:可可西里 更新时间:2023-11-01 01:49:07 24 4
gpt4 key购买 nike

我正在使用 swift-snapshot-testing并发现了一个关于 Generic 函数参数默认值的问题。

框架提供了这样的方法:

func verifySnapshot<Value, Format>(matching value: Value,
as snapshotting: Snapshotting<Value, Format>,
snapshotDirectory: String? = nil) -> String?

其中 Snapshotting 是一个像这样的通用结构:

struct Snapshotting<Value, Format> {}

extension Snapshotting where Value == UIViewController, Format == UIImage {
static var image: Snapshotting<UIViewController, UIImage> {
:
}
}

extension Snapshotting where Value == UIView, Format == UIImage {
static var image: Snapshotting<UIView, UIImage> {
:
}
}

我想创建一个辅助方法,这很有效:

func verify<Value, Format>(matching value: Value,
as snapshotting: Snapshotting<Value, Format>) {
let snapshotDirectory = "/path"

let failure = verifySnapshot(matching: value,
as: snapshotting,
snapshotDirectory: snapshotDirectory)

print(failure ?? "Done!")
}

但是当我想给 snapshotting 一个默认参数值 .image 时,它不会编译错误 Ambiguous reference to member 'image'

func verify<Value, Format>(matching value: Value,
as snapshotting: Snapshotting<Value, Format> = Snapshotting<Value, Format>.image)

我的问题是:Swift 可以为默认参数值推断泛型类型 Format 吗?

最佳答案

这里的主要问题是.image不存在于每个 <Value, Format>一对。它只存在于 <UIViewController, UIImage> , 和 <UIView, UIImage> .要在此处分配默认值,它必须适用于 verify 的所有方式可以调用。

默认参数始终可以表示为参数较少的单独函数,因此您只需添加所需的重载而不是默认值。

func verify(matching value: UIViewController) {
verify(matching: value, as: .image)
}

func verify(matching value: UIView) {
verify(matching: value, as: .image)
}

关于swift - 泛型函数参数默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56256602/

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