问答详情
源自:4-4 泛型约束

能夠將變量的類型泛型約束化嗎?

extension Record{
    public static func <(lhs: Self, rhs: Self) -> Bool{
        return lhs.winningPercent() < rhs.winningPercent()
    }

    public static func ==(lhs: Self, rhs: Self) -> Bool{
        return lhs.winningPercent() == rhs.winningPercent()
    }
}

用上一視頻使用的例子,創建了三個遵守Record這個協議的結構體(BaseballRec, BasketballRec, FootballRec)

其三者的實例(baseTeamRec,basketTeamRec,footTeamRec)是可以兩兩互相比較的,也可以調用isPrizable()方法,但當帶入函數topPrizable時

func topPrizable<T: Record & Prizable>(list: [T]) -> T?

topPrizable(list: [baseTeamRec, basketTeamRec, footTeamRec] )

會提示類型不匹配的錯誤,要怎麼修正呢?

Cannot convert value of type '[Any]' to expected argument type '[_]'

且要將這些實例存成Record的Array也有錯誤,提示Record Protocol 要成爲類型得要用泛型約束,gameRecords的類型要如何定義呢?

let gameRecords: [Record] = [baseTeamRec, basketTeamRec, footTeamRec]

Protocol 'Record' can only be used as a generic constraint because it has Self or associated type requirements

提问者:leavie 2016-09-15 08:43

个回答

  • heiheipingguo
    2016-09-17 18:57:04
    已采纳

    漏了一个关键字,应该是这样:func topPrizable<T: protocol<Record, Prizable>>(list: [T]) -> T?

  • 小火慢炖luky
    2016-09-26 14:30:28

    请 刘老师  出来 解答一下。。。。。。。。。。。。等待

  • heiheipingguo
    2016-09-17 18:47:32

    可以使用聚合协议来定义,就是这样子func topPrizable<T: <Record, Prizable>>(list: [T]) -> T?