Reputation: 143359
How can I define a relationship that specifies that T
supports an Int
subscript in my generic constraint so this function compiles?
func index<T,U>(x:T) -> U {
return x[0] //Invalid capability as expected
}
My first guess is something like T[Int] == U
where I can specify T
can be indexed with an Int
and returns U
, i.e:
func index<T,U where T[Int] == U>(x:T) -> U {
return x[0]
}
But this made up syntax doesn't work. Is there anyway I can specify this relationship either as a generic constraint or a protocol?
Upvotes: 2
Views: 609
Reputation: 17428
You can use a protocol that implements subscript functionality. For example:
protocol Container {
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
func index<T:Container, U where U == T.ItemType>(x:T) -> U {
return x[0]
}
Upvotes: 9