Search code examples
deprecatedarray-mergeswift2

++ is deprecated - "+= 1 is not solving the issue"


After updating Xcode to 7.3 I am having some warnings saying :

'++' is deprecated: it will be removed in Swift 3

The code where the warning appear is a function that merges two arrays:

arr4.append(arr1[i++])

I have tried changing it with :

arr4.append(arr1[i += 1])

but I get an error saying :

Cannot subscript a value of type '[[String]]' with an index of type '()'

The full code is:

let arr1 = [["aaa","111"],["bbb","222"],["ccc","333"]]
let arr2 = [["ddd","444"],["eee","555"],["fff","666"]]

var arr4 = zip(arr1, arr2).reduce([]) { ( newArr, p:(Array<String>, Array<String>)) -> [[String]] in

    var arr = newArr

    arr.append(p.0)
    arr.append(p.1)
    return arr
}

var i = arr4.count / 2
while i < arr1.count {
    arr4.append(arr1[i++]) // WARNING
}

while i < arr2.count {
    arr4.append(arr2[i++]) // WARNING
}
print(arr4)

Solution

  • Use:

    arr4.append(arr1[i])
    i += 1
    

    The motivation for the change is legibility — ensuring that steps are properly spelt out, reducing ambiguity. The result of the expression a += 1 is of type void — it does something, but doesn't evaluate to anything — which is expressed as the empty tuple, (), and cannot be used as an array index.

    (Aside: += 1 also isn't a direct substitution for ++ in C.

        int a = 3;
        int b = a += 1;
        NSLog(@"%d %d", a, b);
    

    ... will produce a different output than the equivalent b = a ++;.)