Episode #127

Swift Operators

10 minutes
Published on July 10, 2014

This video is only available to subscribers. Get access to this video and 572 others.

One of Swift's powerful features is the ability to define custom operators. In this episode we take a look at two examples of custom operators, one for easy regular expression matching, and another for computing the dot product between two vectors.

Episode Links

A Regular Expression Matching Operator

import Foundation

class Regex {
  let pattern: String

  init(_ pattern: String) {
    self.pattern = pattern
  }

  func test(input: String) -> Bool {
    let range = input.rangeOfString(pattern, options: .RegularExpressionSearch)
    return range != nil
  }
}

infix operator =~ {}

func =~(input: String, pattern: String) -> Bool {
  return Regex(pattern).test(input)
}

You can use this simply:

let input = "09182a4" // take out the "a" and it will match
if input =~ "^\\d+$" {
  println("Matches")
} else {
  println("doesn't match")
}

An operator for Dot Product

Given a struct that represents a vector:

struct Vector {
  let x: Float
  let y: Float

  func dotProduct(other: Vector) -> Float {
    return x * other.x + y * other.y
  }
}

You can simplify calling the dot product with a custom operator like this:

let a = Vector(x: 1, y: 8)
let b = Vector(x: 6, y: 2)

infix operator .. {}

func ..(a: Vector, b: Vector) -> Float {
  return a.dotProduct(b)
}

let result = a .. b

println("The dot product is \(result)")

Note that while this feature is very enticing, you should take care not to abuse it. It can harm readability of your code and I would only use this in cases where I used this function Everywhere and I wanted a terse (but not mysterious) syntax.