加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift泛型类型选择不会传播

发布时间:2020-12-14 04:54:39 所属栏目:百科 来源:网络整理
导读:如果我理解正确,Swift可以通过不同的方式确定泛型的实际类型,包括通过返回类型进行匹配.相同(或类似)机制用于消除重载函数的歧义.所以这按预期工作: func getValueT()-T? { return nil}func getValue()-Int? { return 13}let b: Int? = getValue() 运行时,b
如果我理解正确,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 value
protocol GetValue {
    static func getValue() -> Self?
}

// Default implementation
extension GetValue {
    static func getValue() -> Self? {
        return nil
    }
}

// Int implementation
extension Int: GetValue {
    static func getValue() -> Int? {
        return 13
    }
}

// Our generic getGetValue function for any type that implements GetValue
func 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读