No, please read my reply above again.
[1, 2].self
is not a type (or metatype), it's simply [1, 2]
, ie the array itself.
let a = [1, 2]
let b = [1, 2].self.self.self.self.self // Note: zero or more .self here doesn't matter!
print(a) // [1, 2]
print(b) // [1, 2]
print(a.count, b.count) // 2 2
print(a == b) // true
See?
We can take this in two steps:
protocol TypedObject {
var type: Any.Type { get }
}
extension TypedObject {
var type: Self.Type { Self.self } // <-- I've changed this to what I assume you meant.
}
extension Array: TypedObject { } // <-- And this.
print(
[1,2].type == type(of: [1,2,3]),
[1,2].type == type(of: [1,2])
)
The reason that this does not compile is that the default implementation of type
is not satisfying the requirement (because Self.Type
is not Any.Type
) so you either have to do this:
protocol TypedObject {
var type: Any.Type { get }
}
extension TypedObject {
var type: Any.Type { Self.self }
}
extension Array: TypedObject { }
print(
[1,2].type == type(of: [1,2,3]),
[1,2].type == type(of: [1,2])
)
// Will print "true true".
or this:
protocol TypedObject {
associatedtype A
var type: A { get }
}
extension TypedObject {
var type: Self.Type { Self.self }
}
extension Array: TypedObject { }
print(
[1,2].type == type(of: [1,2,3]),
[1,2].type == type(of: [1,2])
)
// Will also print "true true".
I don't really see the point of this since it's essentially just a complicated way of saying
(for the first example):
let foo: Array<Int> = [1, 2]
let bar: Any.Type = type(of: foo)
print(bar == type(of: foo)) // true
or (the second example):
let foo: Array<Int> = [1, 2]
let bar = type(of: foo)
print(bar == type(of: foo)) // true