4

I need a brief and clear explanation about why this is happening.

I used "Conditionally Conforming to a Protocol" which is introduced in swift documentation (link)

I want Array type to conform to my Test Protocol as long as elements in Array conforms to that protocol.

protocol Test {
    var result : String {get}
}

extension Int: Test {
    var result: String {
        return "int"
    }
}

extension Array: Test where Element: Test {
    var result: String {
        return "array"
    }
}

Then, I declared an instance of Array like this.

let array1 = Array<Test>()

print(array1 is Test) // **false**

I thought array1 was supposed to conform Test protocol (true) , but it was found not.

Then, I tried the following way of extension, and it worked.

extension Array: Test where Element == Test {
    var result: String {
        return "array"
    }
}

let array2 = Array<Test>()

print(array2 is Test) // **true**

I thought Array<Test>() meant "array that can take elements conforming to Test protocol", so that this array was supposed to conform to same protocol just like I declared in the first extension.


Question
1. Difference between colon(:) and equal-to operator(==)
- : means only conforming type / == means identical type?
2. Explanation how it works when I declare array instance like Array<Test>()

  • 2
    This is essentially the same issue as in [Protocol doesn't conform to itself?](https://stackoverflow.com/q/33112559/1187415) – In `Array()` the `Element` type is equal to  `Test`, but does not conform to `Test`. – Martin R May 30 '19 at 06:36

0 Answers0