简体   繁体   English

如何指定在Swift中强制执行下标的泛型约束?

[英]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? 如何定义一个关系,指定T支持我的泛型约束中的Int下标,以便此函数编译?

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: 我的第一个猜测类似于T[Int] == U ,我可以指定T可以用Int索引并返回U ,即:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM