I have this bit of code that works just fine and does exactly what I want:
if condition1 { array1 += [array1[in]] } else { array1 += [Int (arc4random_uniform(7))] if array1[i] >= array1[in] { array1[i] += 1 } } //same logic, different condition and array if condition2 { array2 += [array2[in]] } else { array2 += [Int (arc4random_uniform(7))] if array2[i] >= array2[in] { array2[i] += 1 } }
But I do the same thing twice, just with a different condition and a different array. How can I avoid duplicate logic? I tried to pack it as an array of two tuples:
[ (condition1, array1) , (condition2, array2) ]
and I put this in a for loop:
for tuple in [ (condition1, array1) , (condition2, array2) ] { var (condition, array) = tuple if condition { array += [array[in]] } else { array += [Int (arc4random_uniform(7))] if array[i] >= array[in] { array[i] += 1 } } }
and it compiled, but it looks like the array was copied, in other words, changing the "array" did not affect "array1" or "array2". I tried other options using tuple.0 and tuple.1 notation, but couldn't get this to compile. So I tried using NSArrays instead of my own Swift arrays ... but I couldn't figure out how to do it right, and in any case thought there should be an easier way to do this.
Is there a concise way to rebuild my source code so as not to duplicate the logic?
arrays swift
user1224598
source share