Reversing a Range results in Mismatching Types

时光毁灭记忆、已成空白 提交于 2019-12-20 02:29:40

问题


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 declare let range: SomeType = .... I have not been able to find that though. Any ideas?


回答1:


You can use AnySequence to create a "type-erased sequence" which forwards the operations to the underlying sequence, hiding the specifics of the underlying SequenceType:

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 of range.

For Swift 3 and later, replace reverse() by reversed().



来源:https://stackoverflow.com/questions/33529395/reversing-a-range-results-in-mismatching-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!