简体   繁体   中英

Protocol Extension Error Array

I was writing some code from the Apple forum. Everything seems right but I keep getting two errors. Someone please help. The code is below followed by the errors.

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)

在此处输入图片说明

Any is not equatable, so you can't call checkToSeeIfItemsEqual using Any arrays.

I'm not sure what exactly you're trying to do, but I think you might be misunderstanding how equatable works. The types have to be known and identical on both sides of the expression. eg Bool == Bool . If you have an Array, you have no way of knowing what the type of the array's Element is, and so cannot compare them.

If you want to compare two arrays of the same equatable type, you can do this:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM