C. Keith Ray

C. Keith Ray writes about and develops software in multiple platforms and languages, including iOS® and Macintosh®.
Keith's Résumé (pdf)

Friday, October 20, 2017

How can we create an operator to append a value to an array?

This is a sample from my book in progress at LeanPub: What Every Programmer Needs to Know About Swift.

Sometimes you want to be succinct and repetitive — as in appending values to an array. We could create an operator function that modifies the array, but that doesn’t let us use the operator multiple times in the same expression. This is because the temporary values you get in a complex expression are immutable.

precedencegroup AppendPrecedence {
    associativity: left
    lowerThan: TernaryPrecedence
}

infix operator «: AppendPrecedence

func « <T>(lhs: Array<T>, rhs: T) -> Array<T>
{
    var result = lhs
    result.append(rhs)
    return result
}

let x = [1,2,3,4]
let z1 = (x « 5) « 6
print(z1) // prints [1, 2, 3, 4, 5, 6]

let z2 = x « 5 « 6
print(z2) // prints [1, 2, 3, 4, 5, 6]

let z3 = x « 4 + 5 * 9 « 12
print(z3) // prints "[1, 2, 3, 4, 49, 12]"

let z4 = x « 4 < 5 ? 22 : 33 « 12
print(z4) // prints "[1, 2, 3, 4, 22, 12]"

By making the precedence of this operator less than one of the lowest precedences (TernaryPrecedence), we can mix other expressions and still get the results we expect. Though you should use parentheses to make complicated expressions more clear.

No comments:

Post a Comment