Swift泛型类型选择不会传播

Swift泛型类型选择不会传播,第1张

概述如果我理解正确, Swift可以通过不同的方式确定泛型的实际类型,包括通过返回类型进行匹配.相同(或类似)机制用于消除重载函数的歧义.所以这按预期工作: func getValue<T>()->T? { return nil}func getValue()->Int? { return 13}let b: Int? = getValue() 运行时,b将为13.从技术上 如果我理解正确,Swift可以通过不同的方式确定泛型的实际类型,包括通过返回类型进行匹配.相同(或类似)机制用于消除重载函数的歧义.所以这按预期工作:

func getValue<T>()->T? {    return nil}func getValue()->Int? {    return 13}let b: Int? = getValue()

运行时,b将为13.从技术上讲,两个函数签名都是合适的,但后者更适用于请求的返回类型.

让我们添加第二个函数并通过它来隧道调用:

func getGetValue<T>()->T? {    return getValue()}let c: Int? = getGetValue()

运行时,c将为零.实际上,编译器将选择从getGetValue()调用的泛型getValue()实现,这不是我想要的.恕我直言,在getValue()的两个实现之间进行选择时,请求的返回类型应该通过第二个泛型传播,从而产生与第一个示例中相同的行为.

我错过了什么? (Xcode 7.1)

解决方法 我试图显式传播泛型类型,它仍然不起作用(所以你说这是一个问题):

func getGetValue<T>()->T? {    guard let value: T? = getGetValue()    return value}

这是一个稍微不同的方法,但是可能会使用协议获得您正在寻找的东西(使用协议允许我们保留一些类型信息)

// Protocol for getting a valueprotocol GetValue {    static func getValue() -> Self?}// Default implementationextension GetValue {    static func getValue() -> Self? {        return nil    }}// Int implementationextension Int: GetValue {    static func getValue() -> Int? {        return 13    }}// Our generic getGetValue function for any type that implements GetValuefunc getGetValue<T: GetValue>()->T? {    return T.getValue()}let a: Int? = getGetValue() // 13// Making String implement the protocol (It gets the default implementation)extension String: GetValue {}let b: String? = getGetValue() // nil
总结

以上是内存溢出为你收集整理的Swift泛型类型选择不会传播全部内容,希望文章能够帮你解决Swift泛型类型选择不会传播所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1014546.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存