Fred Shmed
Fred Shmed

Reputation: 89

complex ternary expression in swift

I came across the following function which I am having a problem understanding the syntax:

func countUniques<T: Comparable>(array: Array<T>) -> Int {
  let sorted = array.sort(<)
  **let initial: (T?, Int) = (.None, 0)**
  let reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
  return reduced.1
}

I understand ternary expression in swift, but this one I am totally confused:

let initial: (T?, Int) = (.None, 0)

can you please explain how it works?

Upvotes: 2

Views: 114

Answers (1)

Ivan Smetanin
Ivan Smetanin

Reputation: 2039

That's not a ternary expression.

It's a tuple with optional generic parameter that has two cases .none and .some(_), .none means that there is nil.

So let initial: (T?, Int) = (.none, 0) means that you have two parameters in property where the first one is some Comparable and the second one is Int. The first is assigned nil and the second 0.

Upvotes: 5

Related Questions