能夠將變量的類型泛型約束化嗎?
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