反转范围会导致不匹配的类型 [英] Reversing a Range results in Mismatching Types
问题描述
我想使用一个变量来保存通常是某个范围的东西,例如 Range< Int>
,这样我可以使用条件逻辑来改变没有复制/粘贴循环的循环范围。例如:
let range = aNumber%2 == 0? 0 ..< 10:(0 .. <10).reverse()
在范围内{/ * for循环逻辑* /}
行 let range = ...
会导致错误:结果值在'? :'expression has mismatching types'Range< Int>和'ReverseRandomAccessCollection< Range(Int)'
。我会猜想反转范围将导致相同类型的范围或至少一个协议或两个值继承/实现的东西,所以我可以声明让范围:SomeType = ...
。虽然我一直没有找到。任何想法?
您可以使用 AnySequence
创建一个类型擦除序列
,将操作转发到底层序列,隐藏底层 SequenceType
的细节:
let range = aNumber%2 == 0
,所以这是
? AnySequence((0 .. <10))
:AnySequence((0 ..< 10).reverse())
为范围{print(i)}
$ b $ p
$ b $ p
$ ; int>范围
类型。
对于Swift 3然后用
reversed()
替换reverse()
。I want to use a variable to hold what would normally be a range of something, for example
Range<Int>
, so that I can use conditional logic to change the range of a loop without copy/pasting the for loop. For instance:let range = aNumber % 2 == 0 ? 0..<10 : (0..<10).reverse() for i in range { /* for loop logic */ }
The line
let range = ...
will result in the error:Result values in '? :' expression have mismatching types 'Range<Int>' and 'ReverseRandomAccessCollection<Range(Int)'
. I would've guessed that reversing the range would result in the same type of range or at least a protocol or something that both values inherit/implement so I could declarelet range: SomeType = ...
. I have not been able to find that though. Any ideas?解决方案You can use
AnySequence
to create a "type-erased sequence" which forwards the operations to the underlying sequence, hiding the specifics of the underlyingSequenceType
:let range = aNumber % 2 == 0 ? AnySequence ( (0 ..< 10) ) : AnySequence ( (0 ..< 10).reverse() ) for i in range { print(i) }
Both expression in the ternary conditional operator have the same type
AnySequence<Int>
, so that is the type ofrange
.For Swift 3 and later, replace
reverse()
byreversed()
.这篇关于反转范围会导致不匹配的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!