Uncategorized

Quick Swift: Operators

Operators are just a special type of function that can help make your code easier to read. Operators you might be familiar with include +, -, and even ??.

They come in three flavors: prefix, infix, and postfix, depending on where you put them with respect to their arguments:

  • Prefix operators go before their (only) argument
  • Infix operators go between their (two) arguments
  • Postfix operators go after their (only) argument

+, -, and ?? take two arguments, the first referring to the object on the left of the operator, the second referring to the object on the right of the operator. So, the following two lines are theoretically equivalent :

let six = 2 + 4
let alsoSix = +(2, 4)

(Although, technically, because + is defined as an infix operator, you have to use it as such – you can’t call it as a function directly without parentheses around it, eg let alsoSix = (+)(2, 4).)

Below is an example of the definition of an infix operator called ?>

infix operator ?>: AdditionPrecedence
func ?> <T, U>(t: T?, f: (T) -> U) -> (T?) -> U? {
  return { t: T? in
    if let t = t {
      return f(t)
    }
    return nil
  }
}

Which can be used it thusly:

let name: String? = "elliot"
let allCaps: (String) -> String = { return $0.uppercased() }
let newName = name ?> allCaps

In which case newName will equal “ELLIOT” and be of type String?.

When you’re defining an operator you can also give it Precedence and Associativity, which basically determine order of operations when you use multiple operators at a time. However, that’s a bit more advanced, so I’ll refer you to the documentation.

2 thoughts on “Quick Swift: Operators”

  1. Elliot!

    This isn’t very relevant to my day to day work but I absolutely love hearing from you!! I hope you’re well 🙂

    On Tue, Aug 11, 2020 at 12:24 PM schrock {block} wrote:

    > E S posted: ” Operators are just a special type of function that can help > make your code easier to read. Operators you might be familiar with include > +, -, and even ??. They come in three flavors: prefix, infix, and postfix, > depending on where you put them with res” >

    1. Aww thank you Noah! Trying to talk more about my work, but not to worry – I’m going on a cross country camping trip in September that I’ll document here which should be less esoteric!

Leave a comment