• Zion W.
    2019-12-08
    为啥不写成
    func allItemsMatch<Container>(container: Container, anotherContainer: Container)-> Bool where Container.ItemType : Equatable {
    ...
    }
    抛开举例演示的原因。
    展开

    作者回复: 代码都要先试一下,你这个代码是编译不通过的。
    演示里代码的意思是C1可以是遵循Container的数据结构2,C2是遵循Container的实现2,这两个实现是可以不一样的,但是只要他们都遵循Container,并且ItemType一样,ItemType遵循Equatable,就可以应用allItemsMatch方法。

    也就是说C1可能是栈,C2可能是队列。但是只要里面都是Int,我就可以用allItemsMatch方法。

    你写成
    func allItemsMatch<C1: Container>(container: C1, anotherContainer: C1)-> Bool where C1.ItemType : Equatable {
        return true
    }
    是可以编译的,但是这就要求了方法的两个参数都是一种实现类型,比如都是栈,或者都是队列

    
    
我们在线,来聊聊吧