mythz
mythz

Reputation: 143359

How can I specify a generic constraint that enforces a subscript in Swift?

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

Answers (1)

Dash
Dash

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

Related Questions