gpt4 book ai didi

ios - 具有关联类型和泛型的 Swift 协议(protocol)调用错误的函数

转载 作者:行者123 更新时间:2023-11-28 12:49:45 25 4
gpt4 key购买 nike

我尽量让我的问题非常简单。我整天都在努力让它工作,但没有运气。我有两个协议(protocol)。可解码和可请求。

protocol Decodable { }
struct D: Decodable { }

protocol Requestable {
associatedtype Model
}

extension Requestable {
func returnValue() {
Utils.doSomething(Model)
}
}

还有一个类 Utils

class Utils {
static func doSomething<T>(param: T) {
print("Default")
}

static func doSomething<T: Decodable>(param: T) {
print("Decodable")
}

static func doSomething<T: Decodable>(param: [T]) {
print("Decodable Array")
}
}

我创建了一个实现 Requestable 的结构 R,并将类型别名 Model 赋予了 String

struct R: Requestable {
typealias Model = String
}

当我运行 R().returnValue() 函数时,它会打印 Default。正如预期的那样。

我创建了一个实现 Requestable 的结构 R2,并将类型别名 Model 赋予了正在实现 Decodable 的 D

struct R2: Requestable {
typealias Model = D
}

当我运行 R2().returnValue() 函数时,它会打印 Default。但我期望它会打印 Decodable,因为模型 D 符合 Decodable

我创建了一个实现 Requestable 的结构 R3,并将类型别名 Model 赋予 [D],其中数组元素实现了 Decodable

struct R3: Requestable {
typealias Model = [D]
}

当我运行 R3().returnValue() 函数时,它会打印 Default。但我期待它会打印 Decodable Array 因为模型 D 符合 Decodable

感谢任何形式的帮助。

更新

在这种情况下,使用 AnyRequestable 并在运行时检查将不起作用,因为在实际代码中,Generic 是返回值,无法动态检查。

在真正的代码函数中签名是这样的

public static func ResponseSerializer<M>() -> ResponseSerializer<M, NSError> {}
public static func ResponseSerializer<M: Decodable>() -> ResponseSerializer<M, NSError> {}
public static func ResponseSerializer<M: Decodable>() -> ResponseSerializer<[M], NSError> {}

最佳答案

预期的结果。你忘了申报 Decodable符合您的 Model关联类型。这应该修复它:

protocol Requestable {
associatedtype Model: Decodable
}

编辑: 阅读您的评论,我现在明白您的问题了。问题是,你所要求的需要运行时,没有办法静态实现它:

class Utils {
static func doSomething<T>(param: T) {
if let param = param as? Decodable {
print("Decodable")
} else {
print("Default")
}
}
}

想一想;当您编译代码时,在 returnValue 的范围内,编译器只知道 Model是关联类型,仅此而已。您要么明确声明符合 Decodable ,或者编译器采用默认大小写,即 <T> .

关于ios - 具有关联类型和泛型的 Swift 协议(protocol)调用错误的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824316/

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