gpt4 book ai didi

generics - Swift 如何防止某些泛型重载,例如整数类型的 Range.subscript?

转载 作者:行者123 更新时间:2023-11-28 05:31:10 25 4
gpt4 key购买 nike

类型为 Range 的 Swift 文档状态:

Like other collections, a range containing one element has an endIndex that is the successor of its startIndex; and an empty range has startIndex == endIndex.

Axiom: for any Range r, r[i] == i.

Therefore, if T has a maximal value, it can serve as an endIndex, but can never be contained in a Range<T>.

It also follows from the axiom above that (-99..<100)[0] == 0. To prevent confusion (because some expect the result to be -99), in a context where T is known to be an integer type, subscripting with T is a compile-time error::

// error: could not find an overload for 'subscript'…   
println( Range<Int>(start:-99, end:100)[0] )

However, subscripting that range still works in a generic context::

func brackets<T:ForwardIndexType>(x: Range<T>, i: T) -> T {
return x[i] // Just forward to subscript
}
println(brackets(Range<Int>(start:-99, end:100), 0)) // prints 0

我们如何在我们自己的泛型类中实现这种行为?我无法仅从 subscript 的定义中理解它是如何工作的。 :

subscript (position: T) -> T { get }
subscript (_: T._DisabledRangeIndex) -> T { get }

谁能给我解释一下?

最佳答案

以下代码的行为与内置 Range 相同.

struct MyRange<T: ForwardIndexType> {
subscript (position: T) -> T {
return position
}
subscript (_: T._DisabledRangeIndex) -> T {
fatalError()
}
}

MyRange<String.Index>()["foo".startIndex] // no problem
MyRange<Int>()[0] // < [!] error: could not find an overload for 'subscript' that accepts the supplied arguments

似乎Int._DisabledRangeIndexInt , 和 Int16._DisabledRangeIndexInt16等等。

T._DisabledRangeIndexT 相同, MyRange<T>最终有 2 个冲突 subscript导致编译错误的定义。

关于generics - Swift 如何防止某些泛型重载,例如整数类型的 Range.subscript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28276004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com