Not sure how to avoid code duplication here

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?

+8
arrays swift
source share
2 answers

Curry it!

 func func1(var a: [Int]) -> [Int] { a += [a[in]] return a } func func2(var a: [Int]) -> [Int] { a+= [Int (arc4random_uniform(7))] if a[i] >= a[in] { a[i] += 1 } return a } func function(condition: Bool) -> [Int] -> [Int] { switch condition { case true: return func1 case false: return func2 } } array1 = function(condition1)(array1) array2 = function(condition2)(array2) 

(the same inout tags that mentioned by andyvn22 can apply here as well).

+4
source share
 func alteredArray(var array:[Int], condition: Bool) -> [Int] { if condition { array += [array[in]] } else { array += [Int (arc4random_uniform(7))] if array[i] >= array[in] { array[i] += 1 } } return array } array1 = alteredArray(array1, condition1) array2 = alteredArray(array2, condition2) 

Or, if you feel concise, rename the function, make an array a inout parameter, delete return and name it as:

 alterArray(&array1, condition1) alterArray(&array2, condition1) 
+1
source share

All Articles