简体   繁体   中英

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 , ie:

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?

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]
}

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