leavie
2016-09-15 08:43
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
漏了一个关键字,应该是这样:func topPrizable<T: protocol<Record, Prizable>>(list: [T]) -> T?
请 刘老师 出来 解答一下。。。。。。。。。。。。等待
可以使用聚合协议来定义,就是这样子func topPrizable<T: <Record, Prizable>>(list: [T]) -> T?
玩儿转Swift 2.0(第四季)
14417 学习 · 25 问题
相似问题