2016-10-10 31 views
2

我正在从苹果论坛写一些代码。一切似乎都正确,但我不断收到两个错误。有人请帮忙。代码如下,然后是错误。协议扩展错误数组

protocol Container{ 
associatedtype ItemType 
mutating func append(item: ItemType) 
var count:Int{get} 
subscript(i:Int)->ItemType{get} 
} 

extension Array: Container {} 

func checkToSeeIfItemsEqual<C1:Container, C2:Container>(container1:C1, container2:C2) -> Bool where C1.ItemType == C2.ItemType, C1.ItemType:Equatable{ 

if container1.count != container2.count{ 
    return false 
} 
for i in 0..<container1.count{ 
    if container1[i] != container2[i]{ 
     return false 
    } 
} 
return true 
} 

var damnArray = [1, 2, 4] 
var damnArray2 = [1, 2, 4] 
let theBool = checkToSeeIfItemsEqual(container1: damnArray, container2: damnArray2) 
print(theBool) 

enter image description here

+0

您的append方法定义略有不同。你需要添加一个下划线:mutating func append(_ item:ItemType)。但其他的东西也是错误的...我没有使用任何类型的数组 –

+0

我想它可能会在试图查看'Any'是否可以等同时出现异常 –

回答

0

任何不equatable,所以你可以不使用任何阵列打电话checkToSeeIfItemsEqual。

我不确定你到底想要做什么,但我想你可能会误解equatable的工作原理。类型必须在表达式的两边都是已知的和相同的。例如Bool == Bool。如果你有一个数组,你无法知道数组元素的类型是什么,所以无法比较它们。

如果要比较相同equatable类型的两个数组,你可以这样做:

func arraysAreEqual<ElementType: Equatable>(firstArray: [ElementType], secondArray: [ElementType]) -> Bool { 

    guard firstArray.count == secondArray.count else { 
     return false 
    } 

    for i in 0..<firstArray.count{ 
     if firstArray[i] != secondArray[i]{ 
      return false 
     } 
    } 
    return true 
} 
+0

好吧,我更新了代码,仍然得到了同样的第一个错误,谈论所需的追加。 –

+0

O nvm我想通了 –