问题
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